A community of developers

React

How to Get Input Value on Button Click in React.js

In this post, we’ll see by example how to get the value of the input field when clicking a button in React,js so let’s get started

As a prerequisite, you need to be familiar with JavaScript and you also need to have a React app generated using create-react-app or simply have added React.js library to your index.html file via a typical script tag.

Getting the Value of Input Field When Clicking a Button

Let’s now see our example which contains an input field and a button and we’ll see how to get and display the value of the input field when you click the HTML button.

Open the App.js file and make sure you have the following imports:

import React from 'react';
import ReactDOM from 'react-dom';

You simply need to import React and ReactDOM:

Next, you need to add state to your React component using the following code:

class App extends React.Component{
    constructor(props)
    {
      super(props);
      this.formState = { value : '' };
    }
}

The formState variable will be used to store the state of the form.

Next, let’s define two methods that will be used to handle submitting the form and updating the input field:

class App extends React.Component{
    constructor(props)
    {
      super(props);
      this.formState = { value : '' };
      this.onSubmit = this.onSubmit.bind(this);
      this.updateState = this.updateState.bind(this);
    }
    onSubmit(e)
    {
      e.preventDefault();
      if(this.formState.value)
      {
        console.log(this.formState.value);
      }
    }
    updateState(e){
      this.formState = { value: e.target.value };   
    }
}

Next, let’s render the form:

class App extends React.Component{


    // [...]

    render()
    {
      return (
         <form onSubmit = { this.onSubmit } >
           <input type="text" onChange = { this.updateState } />
           <input type="submit" value=" Get Value" />
         </form>
      )
    }
  }

  ReactDOM.render(<App />, document.getElementById('root'));

We simply bind the onSubmit method to the onSubmit event of the form and the updateState method to the onChange event of the input field which gets fired when the value of the input field changes.

When the value of the input field changes, we simply update the state accordingly, and when the form is submitted we display the value of the input field on the console.

That’s we have seen how we can track and get the value of an input field using React state.

In the example, you’ve seen how to get the value of an input field in React.js when clicking a button.

Leave a Reply

Skip to toolbar