Step 6
To ensure the form elements use the component state, we will make a two-way integration so that
- the form element "value" is always the value stored in component state
- the component state is updated when the form value changes (as a result of user interaction)
For each HTML form, update value
and onChange
attributes; for example for input
element for "course" make the following changes
<input
type="text"
name="course"
placeholder="Course"
+ value={this.state.course}
+ onChange={this.handleChange}
/>
Since the value attribute is set on our form element, the displayed value will always be this.state.course
, making the Component state the source of truth. The handleChange
(which we have not implemented yet) will run on every keystroke to update the Component state as the user types.
Here is the complete updated render
method
render() {
return (
<div>
<a href="/" className="close-create-meeting">
Close
</a>
<form className="create-meeting-form">
<div className="create-meeting-details">
<input
type="text"
name="course"
placeholder="Course"
value={this.state.course}
onChange={this.handleChange}
/>
<input
type="text"
name="instructor"
placeholder="Instructor"
value={this.state.instructor}
onChange={this.handleChange}
/>
<input
type="text"
name="time"
placeholder="Meeting Times"
value={this.state.time}
onChange={this.handleChange}
/>
<input
type="url"
name="link"
placeholder="Meeting Link"
value={this.state.link}
onChange={this.handleChange}
/>
<button>Add Meeting</button>
</div>
</form>
</div>
);
}
We must now implement the handleChange
method:
handleChange(event) {
this.setState({ [event.target.name]: event.target.value });
console.log(this.state);
}
The console.log
is for sanity check during development. We will remove it after testing that the method behaves as expected. Don't forget to bind the method to the CreateMeeting
class; add the following statement to its constructor:
this.handleChange = this.handleChange.bind(this);
Save the file and revisit the app in your browser.
With a controlled component, the input's value is always driven by the Component's state. This may seem unnecessary to you but notice we can now pass the values in out form element to other UI elements too, or reset it from other event handlers.