Search code examples
javascriptreactjscontenteditable

How to Apply maxLength to editable div using react?


I'm trying to simulate maxlength property to editable div using react, I have tried to enforce the length by triggering keyPress and check innerText size, then compare it to maxLength

Using this helper :

function handlesInputMaxLength (event, maxSize = INPUT_MAX_LENGTH) {
  let text = event.target.textContent;
  if (text.length >= maxSize) {
    event.preventDefault();
    return false;
  }
};

             <span
                  contentEditable="true
                  onKeyPress={handlesInputMaxLength}
                  onInput={handleGreetingChange}
                >
                  {greetingMessage}
             </span>

It works when the user type, but it fails when the user copy & past the text, Also, I have tried to capture the text from onPast event, and I tried to pass the exact helper for handlesInputMaxLength but It keeps failing.

Any advice to handle this issue?

Update(1)

My use case only depends on editable div to work with the below style, input and textarea are not usable options.

enter image description here


Solution

  • Make a state:

    const [value, setValue] = useState('')
    

    define MAX_LENGTH:

    const MAX_LENGTH = 10;
    

    and on onChange:

    <input
      value={value}
      onChange={e => value.length < MAX_LENGTH && setValue(e.target.value)}
      / >