React: Creating a Controlled Form
Randy Rivera
Posted on October 19, 2021
- FreeCodeCamp in our last challenge showed us that React can control the internal state for certain elements like input and textarea, which makes them controlled components. This applies to other forms elements as well including the regular HTML form element.
- Here
MyForm
component is set up with an emptyform
. As you can see it has thetype
set tosubmit
indicating it is the button controlling the form. They want us to add theinput
element in theform
and set itsvalue
andonChange()
attributes like the last post.
class MyForm extends React.Component {
constructor(props) {
super(props);
this.state = {
input: '',
submit: ''
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({
input: event.target.value
});
}
handleSubmit(event) {
// Change code below this line
// Change code above this line
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
{/* Change code below this line */}
{/* Change code above this line */}
<button type='submit'>Submit!</button>
</form>
{/* Change code below this line */}
{/* Change code above this line */}
</div>
);
}
}
- We should also call
event.preventDefault()
in the submit handler, to prevent default form submit behavior which will refresh the web page. Lastly they want us to create an
h1
tag after theform
which renders thesubmit
value from the component'sstate
.Answer:
class MyForm extends React.Component {
constructor(props) {
super(props);
this.state = {
input: '',
submit: ''
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({
input: event.target.value
});
}
handleSubmit(event) {
event.preventDefault()
this.setState({
submit: this.state.input
})
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<input value = {this.state.input} onChange = {this.handleChange}/>
<button type='submit'>Submit!</button>
</form>
<h1>{this.state.submit}</h1>
</div>
);
}
}
💖 💪 🙅 🚩
Randy Rivera
Posted on October 19, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.