by Sai gowtham

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, we need to 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:

App.js
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.

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.

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
130,921 students enrolled
21 hours of video content
View Course