In the following code:
-
Why are we passing “event” parameter in handleSubmit() function, although there is no use of event parameter inside the body of this function. If we do not pass this parameter error occurs. Kindly explain this matter.
-
In handleChange(), we changed state by using => input: event.target.value.
kindly explain how “event” generated and what it stores. what is target and value and how are we using them in this scenario.
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
event.preventDefault()
this.setState({
submit: this.state.input
})
// change code above this line
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
{ /* change code below this line */ }
<input value = {this.state.input} onChange = {this.handleChange} />
{ /* change code above this line */ }
<button type='submit'>Submit!</button>
</form>
{ /* change code below this line */ }
<h1>{this.state.submit}</h1>
{ /* change code above this line */ }
</div>
);
}
};
**Your browser information:**
User Agent is: <code>Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36</code>.
**Challenge:** Create a Controlled Form
**Link to the challenge:**
https://www.freecodecamp.org/learn/front-end-libraries/react/create-a-controlled-form