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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *