How to Only Allow Numbers to be Entered in an Input in React?

Sometimes, we want to only allow numbers to be entered in an input in React.

In this article, we’ll look at how to only allow numbers to be entered in an input in React.

Only Allow Numbers to be Entered in an Input in React

To only allow numbers to be entered in an input in React, we can set the pattern attribute of the input to only allow digits to be inputted.

Then in the onChange handler, we only set the value of the input when the inputted value is valid.

For instance, we write:

import React, { useState } from "react";

export default function App() {
  const [val, setVal] = useState(0);

  return (
    <div>
      <input
        type="text"
        pattern="[0-9]*"
        value={val}
        onChange={(e) =>
          setVal((v) => (e.target.validity.valid ? e.target.value : v))
        }
      />
    </div>
  );
}

We create the val state with the useState hook.

And we set that as the value of the value prop.

Then we add the pattern attribute and set it to a regex that only matches digits.

Finally, the onChange prop is set to a function that calls setVal with a function that takes the existing value of val, which is v.

And we check if the inputted value is valid with e.target.validity.valid .

If it is, we return the current inputted value, which is stored in e.target.value.

Otherwise, we return the current value of val which is v.

Conclusion

To only allow numbers to be entered in an input in React, we can set the pattern attribute of the input to only allow digits to be inputted.

Then in the onChange handler, we only set the value of the input when the inputted value is valid.