React makes it easy to manipulate data using forms.
Form input values can be set to state values and then updated via React events. Defining a form’s input value via state is considered a controlled component.
For controlled inputs you will need a corresponding state and then a class method to update that state with changes.
Let’s walk through a quick example with CodePen. If you don’t know how to set up CodePen with React, you can check out this story.
Let’s also add Boostrap 4 to our CodePen so our forms aren’t so plain.
Add this to your JS file:
class App extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div className="form-group container">
<label>Controlled Form Input</label>
<input type="text"
className="form-control"
aria-describedby="emailHelp"
placeholder="Update input here" />
<large className="form-text text-muted">
Form Output
</large>
</div>
);
}
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
Right now our form input is not controlled- meaning that the value of the form input is not determined by the state. Let’s add a state value for the form making it a controlled form.
Declare the state value in your constructor.
constructor(props) {
super(props);
this.state({input: ''});
}
Then let’s pass the state input value down to the value of the email form and as the value of our output text.
<input type="text"
className="form-control"
aria-describedby="emailHelp"
placeholder="Update input here"
value={this.state.input}/>
<large className="form-text text-muted">
{this.state.input}
</large>
Now notice how the value of the form reflects the state, but the form value doesn’t update. That’s because we don’t have a method that will update state. Let’s add a method to update state, and pass it down using the onChange event handler.
Add the method to your constructor.
constructor(props) {
super(props);
this.state = ({input: ''});
this.formUpdate = this.formUpdate.bind(this);
}
Now define the formUpdate method.
formUpdate(event) {
this.setState({input: event.target.value});
}
The formUpdate function needs to be called whenever a change is made to the form input. Use the onChange react event to trigger the formUpdate method.
<input type="text"
className="form-control"
aria-describedby="emailHelp"
placeholder="Update input here"
value={this.state.input}
onChange={this.formUpdate}/>
Every time a change happens to the form the formUpdate method will be called with the event object. From the event object we can pull the form value using event.target.value.
Let’s take a look at what is going on here: