Forward Advance Learning

Handling Forms

There are two ways of dealing with forms in React.

either...

  1. We can use a stateful component, and bind the form values to state, or...
  2. We can use a stateless component, store the data in the form, and pull it out on submit.

Both are good options, and you'll want to be aware of both of them.

Binding Forms to State

Say we have an input field. When the change event is fired on the component, we pull the value out of the component, and store it in state.

We can also optionally go the other way, and bind the current value to the value property of the input field.

Here's a catName input field:

<input
onChange={(evt) => this.setState({catName: evt.target.value})}
value={this.state.catName}/>

To handle the form submission, we bind to the onSubmit event. We might then call a method on the parent:

Here that is in context:

See the Pen React Stateful Form Demo by Nicholas Johnson (@superluminary) on CodePen.

Add another field to the form and bind it.

Stateless Forms

The other option is to store form data actually in the form, until we're ready to use it, typically onSubmit. We use a thing called a template ref to get access to the input element itself, like so:

<input ref={(el)=>catInput=el} />

The value lives only in the form, but we can get it out again, just by getting the element.value.

Here it is in action:

See the Pen React StateLess Form Demo by Nicholas Johnson (@superluminary) on CodePen.

Add another field to the form and bind it.

Exercise Hero Editor

Assume we have a hero object in our App component.

Create a HeroEdit form that can edit that hero. Pass the hero into it via props. Be careful with immutability here. When the hero editing is complete, bind an onSubmit event to the form (remember to call event.preventDefault() here, or the form will really submit). Have the submit event pass the new, modified hero back up to the app.

For bonus points, create a component that can render the hero.