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

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more