DEV Community

Ryan Munil Lee
Ryan Munil Lee

Posted on

How to limit input length or lines in React-codemirror

Codemirror is a powerful library that allows users to integrate a production-ready code editor into their projects. It’s a huge library with great thorough documentation, but it’s not something you can read in one sitting.

TLDR;

How to limit the length of doc:

 const lengthLimit = useCallback((tr: any): boolean => {
    // NOTE: limiting the length to 100 characters.
    return tr.startState.doc.length + tr.newDoc.length < 200;
  }, []);

<CodeMirror
  value={value}
  extensions={[
    EditorState.changeFilter.of(lengthLimit)
  ]}
  onChange={(value) => setValue(value)}
/>
Enter fullscreen mode Exit fullscreen mode

Source [1], [2]

Similarly, this is how you limit line numbers.

const handleLengthLimit = () => {
   // doc will only update with the newDoc’s line number <= 10
   return tr.newDoc.lines <= 10;
}

<CodeMirror
      extensions={[                  
          EditorState.changeFilter.of(handleLengthLimit),
      ]}
      onChange={handleChange}                      
/>
Enter fullscreen mode Exit fullscreen mode

In-depth

React-codemirror is the most widely used React component for Codemirror. It uses Codemirror 6 behind the scene. However, it has lots of known limitations because Codemirror does not behave in a React way. (It was there before React.)

As of Mar, 2023, React-codemirror editor is currently a uncontrolled component

So when most of React Developer would want to achieve something like this:

User input -> update input state -> mutate input state using useMemo or useEffect -> update input state -> rerender with thew new input

The above wouldn’t work since the component is uncontrolled. So the work around is going to be:

User input -> intercept input and do your stuff with EditorState.changeFilter or EditorState.transactionFilter -> update state -> rerender

If you’re using it for a production feature at your work. I highly recommend you to do a DIY React component by following this article.

About

If you run into the same problem and this article helped you a bit please:
follow my Github Repo
And check out my silly project Typing Brain

Top comments (0)