React - get number value from an input

0 points
Created by:

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 store¬†username¬†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 (
        <label>insert number: </label>
        <input type="text" ref={inputRef} onChange={handleChange}></input>

const root = document.querySelector('#root');
ReactDOM.render(<App />, root );

Related posts

Alternative titles

  1. React - parse input value to a number
  2. React - get integer value of an input element
  3. React - get float value of an input element
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.


React - get number value from an input
Native Advertising
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

‚̧ԳŹūüíĽ ūüôā