EN
React - get value of an input element
0
points
In this article, we would like to show you how to get value of an input element in React.
There are two ways to get an input element value:
- using input reference current value,
- using event target value.
1. Get input reference current value
In this solution we use:
useState
hook - to storeusername
value as component's state,useRef
hook - to create input reference to operate on.
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 [username, setUsername] = React.useState('Your username');
const inputRef = React.useRef();
const handleChange = () => {
setUsername(inputRef.current.value);
};
return (
<div>
<h2>{username}</h2>
<div>
<label>insert username: </label>
<input type="text" ref={inputRef} onChange={handleChange}></input>
</div>
</div>
);
};
const root = document.querySelector('#root');
ReactDOM.render(<App />, root );
2. Get event target value
In this solution, useState
always stores the current value of an input.
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 [username, setUsername] = React.useState('Your username');
const handleChange = (event) => {
setUsername(event.target.value);
};
return (
<div>
<h2>{username}</h2>
<div>
<label>insert username: </label>
<input type="text" onChange={handleChange}></input>
</div>
</div>
);
};
const root = document.querySelector('#root');
ReactDOM.render(<App />, root );
Note:
For more information about updating the useState check the related posts.