Languages
[Edit]
EN

React - get number value from an input

0 points
Created by:
Dirask Community
5610

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 (
    <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 );

Related posts

ReactJS

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.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé

Join