Categories
React Answers

How to only allow numbers in a number input in React?

Spread the love

Sometimes, we want to only allow numbers in a number input in React.

In this article, we’ll look at how to only allow numbers in a number input in React.

How to only allow numbers in a number input in React?

To only allow numbers in a number input in React, we can check for the key that’s pressed.

For instance, we write

<input
  onKeyPress={(event) => {
    if (!/[0-9]/.test(event.key)) {
      event.preventDefault();
    }
  }}
/>

to set the onKeyPress prop to a function that checks the key that’s pressed with event.key.

If it’s not 0 to 9, then we call preventDefault to stop the character from being appending to the input value.

Conclusion

To only allow numbers in a number input in React, we can check for the key that’s pressed.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.