EN
React - get number value from an input
0
points
In this article, we would like to show you how to get number value from an input in React.
In below example we use:
useState
hook - to storeusername
value as component's state,useRef
hook - to create input reference to operate on,parseInt
- to parse string value from an input reference to the integer.
To get the value of an input we assign the reference using the input's ref
property. Then we can get the reference value with inputRef.current.value
and set the username
to it using setUsername
method.
Runnable example:
// ONLINE-RUNNER:browser;
// Note: Uncomment import lines while working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';
const App = () => {
const [number, setNumber] = React.useState(20);
const inputRef = React.useRef();
const handleChange = () => {
setNumber(parseInt(inputRef.current.value)); // for float numbers use parseFloat
};
return (
<div>
<h2>{number}</h2>
<div>
<label>insert number: </label>
<input type="text" ref={inputRef} onChange={handleChange}></input>
</div>
</div>
);
};
const root = document.querySelector('#root');
ReactDOM.render(<App />, root );