React JS – How to Allow Numbers in Textbox?

I am explaining you, how to allow only numbers in textbox in React JS. I am giving you simple example that will allow only numbers in input field react.
Below example, I write that code on change event on inputbox. I take one text field for number and you can enter only number in that textbox. when you write any text in that text box so only number will write.

Example :


import React, { useState } from "react";
import "./styles.css";

export default function App() {
  const [numbers, setNumbers] = useState();

  const handleChange = (e) => {
    const value = e.target.value.replace(/\D/g, "");
    setNumbers(value);
  };

  return (
    <div className="App">
      <h1>Numbers:</h1>
      <input value={numbers} onChange={handleChange} />
    </div>
  );
}

Output :

Leave a Reply

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

58 − = 56