Feature: maxLength
See original GitHub issueSetting a maxlength for an editor was something that was quite complicated using Draft.js. It’s also a common need - particularly for developers relying on an editor primarily for plaintext functionality (as a replacement for <textarea />
).
I see that there’s some WIP work being done on LexicalCharacterLimitPlugin but testing this feature out in the playground seems to show a different behavior than I expected - rather than limiting input it simply highlights input that’s outside the character limit -
I also tried to poke around the source code for how I might implement this myself. My current, very naive implementation:
const LexicalMaxLengthPlugin = ({ maxLength }) => {
const [editor] = useLexicalComposerContext();
useEffect(() => {
editor.registerTextContentListener(textContent => {
if (textContent.length > maxLength) {
editor.update(
() => {
$getSelection().deleteCharacter(true);
},
{
tag: 'history-merge',
},
);
}
});
}, [editor]);
return null;
};
this has many problems (I wasn’t really expecting it to work)
- very slow to delete excessive characters
- using a bad update pattern
- even with the
history-merge
tag, the history stack is broken. A keypress to enter a character beyond the maxlength is still added to the stack.
I’m curious if functionality to mimic the behavior of <textarea maxlength=""
can be accomplished using Lexical as it exists today, or if there will need to be some new APIs implemented. In particular without some pretty tedious and potentially slow node manipulation it’s not clear to me how one could truncate excess characters in a single update.
My team is trying to be an early adopter of Lexical - we’re in the process of migrating our application to React 18 and draft.js is partially blocking that. Thanks!
Issue Analytics
- State:
- Created a year ago
- Comments:13 (6 by maintainers)
Top GitHub Comments
Check out https://github.com/facebook/lexical/pull/2254!
It should definitely be possible to do this. I might take a stab at hacking something together here!