Last updated: Apr 6, 2024
Reading time·2 min
To create a numeric input with min and max validation in React:
type
set to number
.onChange
event handler on the input field.import {useState} from 'react'; const App = () => { const min = 1; const max = 100; const [value, setValue] = useState(1); const handleChange = event => { const value = Math.max(min, Math.min(max, Number(event.target.value))); setValue(value); }; console.log(value); console.log(typeof value); return ( <div> <h2>Min 1 / Max 100</h2> <h3>1500 / -50</h3> <input type="number" placeholder="Your fav number" value={value} onChange={handleChange} /> </div> ); }; export default App;
We used the useState hook to keep the value in the component's state.
Every time the value of the input type number
changes, we use the
Math.max()
function to get a number from min
up to max
.
Math.max
function takes zero or more numbers and returns the largest of the given numbers.We used the
Math.min()
function to get a number between the predefined max
and what the user typed
in.
Math.min
function returns the lowest value from the zero or more provided numbers.The example above only allows for numbers between 1
and 100
.
If the user tries to type in a number lower than 1
, we simply set the
predefined min
value to the state variable.
On the other hand, if the user tries to type in a larger value than the max
,
we set the state variable to the predefined max
.
In all other cases, the state variable is set to the number the user provided.
I've also written an article on how to create a numbers-only input field.