reactjsinputevent-handlingkeydownonkeydown

Can't use any key after e.preventDefault() on keyDown in React


I need to stop users from typing more than 4 digits in an input. Calling e.preventDefault() works fine with onKeyPress, but I don't want to use it because it's deprecated. Using onKeyDown works, but after calling e.preventDefault(), the user can't delete the text, that input is now "frozen". I understand that it's by design. Is there a better way to stop the user from typing more than 4 digits but still to allow the deletion of the text?


Solution

  • Have you attempted adding the maxLength="4" attribute to your input?

    https://www.w3schools.com/tags/att_input_maxlength.asp