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


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.

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