How to get an input field value in React
In this tutorial, we are going to learn how to get the value of an input field in react.
Consider we have a component like this.
import React from "react";
class App extends Component {
state = {
name: "" };
render() {
return (
<div>
<input placeholder="Enter name" /> <button>Log value</button>
</div>
);
}
}
export default App;
Now, we need to get the above input field value by clicking on the button.
Getting input value
To get input field value in React, add a onChange
event handler to the input
field (or element).Inside the onChange
event handler method we can access an event
object which contains a target.value
property which is holding the value that we have entered inside the input field.
Example:
import React from "react";
class App extends Component {
state = {
name: ""
};
handleInput = event => {
this.setState({ name: event.target.value }); };
logValue = () => {
console.log(this.state.name); };
render() {
return (
<div>
<input onChange={this.handleInput} placeholder="Enter name" /> <button onClick={this.logValue}>Log value</button>
</div>
);
}
}
In the above code, we are storing the input field value in this.state.name
property, so that when we click on a Log value
button we can see the value that we have entered.
Getting value using Hooks
Similarly, we can use the above procedure to get the input field value using hooks.
import React, { useState } from "react";
function App() {
const [name, setName] = useState(" ");
const handleInput = event => {
setName(event.target.value); };
const logValue = () => {
console.log(name);
};
return (
<div>
<input onChange={handleInput} placeholder="Enter name"/> <button onClick={logValue}>Log value</button>
</div>
);
}
In the above code, we are initializing a useState()
hook to store the input field value.