Home Reactjs How to get input field value on button click in reactjs?

How to get input field value on button click in reactjs?

by therichpost
6 comments
reactjs

Hello, welcome to therichpost.com. In this post, I will tell you, How to get input field value on button click in reactjs? Reactjs is a Javascript Library to build user interface.

In this post, I made simple form and input field and input button. On button click, I am getting the input box value and this is tricky and in future post, I will do more this form.

Here is the working code and you need to add this into your index.js file:
import React from 'react';
import ReactDOM from 'react-dom';

class Hello extends React.Component{
    constructor(props)
    {
      super(props);
      this.state = {value: ''};
      this.addValue = this.addValue.bind(this);
      this.updateInput = this.updateInput.bind(this);
    }
    
    addValue(evt)
    {
      evt.preventDefault();
      if(this.state.value !=undefined)
      {
        alert('Your input value is: ' + this.state.value)
      }
    }
    updateInput(evt){
      this.state={value: evt.target.value};   
        }
    
    render()
    {
      return (
      <form onSubmit={this.addValue}>
      <input type="text" onChange={this.updateInput} /><br/><br/>
      <input type="submit" value="Click Me :)"/>
      </form>
      )
    }
  }

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

 I will do this post in parts and I can say this is the first part and In future posts, I will do more with reactjs. If you have any query related to this post then please comment below.

You may also like

6 comments

Henk April 18, 2019 - 10:47 am

poepie

Reply
Ajay Malhotra April 21, 2019 - 7:50 am

Thank you

Reply
Sarthak August 10, 2019 - 5:21 pm

You should not update the state directly. Instead use this:

updateInput(evt){
const value = evt.target.value;
this.setState({ value });
}

instead of

updateInput(evt){
this.state={value: evt.target.value};
}

Reply
Ajay Malhotra August 10, 2019 - 5:24 pm

good one 🙂

Reply
Samuel December 30, 2022 - 11:03 am

Please, how do I master React. It’s looking as it it’s very hard

Reply
therichpost December 30, 2022 - 11:32 am

Just doing practice.

Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.