I’ll be sharing a technique on how to easily handle form data in React.

You need 3 steps to easily manage the data of your form.

Click here to share this article on LinkedIn »

Step 1: Initialize state

Let’s say you have a form with movie & price fields, add it to your initial state:

constructor () {

this.state = {

movie: '',

price: ''

}

}

This will be your source of data. In JQuery , you’ll have to get the data from your html input fields. In React, you’ll now get your data here in the state.

Step 2: Add the [name] attribute to your fields

Add the [ name ] attribute to movie & price fields.

For movie field, put movie as value of [ name] attribute.

For price field, put price as value of [ name] attribute.

<input name='movie' />

<input name='price' />

Step 3: Create a function to update your states

Create a function and let’s call it handleChange .

handleChange (event) {

this.setState( [event.target.name]: event.target.value )

}

The form fields should call the handleChange function with the onChange event.

<input name=’movie’ onChange={event => this.handleChange(event)} />

<input name='price' onChange={event => this.handleChange(event)} />

Then that’s it! Your state will now get updated every time you change the values of the input fields of your form.

With these 3 steps, whatever you change in your fields, it’ll automatically update your state. (This is pretty handy specially if you have like more than 10 fields in your form.) So when you are ready for form submission, the data is ready in the state. No need to fetch it from each fields of your form.