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
this.setState(state=>({submit:state.input}))
event.preventDefault()
// 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>
);
}
}
code is working fine without this line :- value={this.state.input}
then why we should add it
HTML <input> elements have a value attribute, as in, what is typed into the input. So the value of the input is whatever state.input is, and when the user types into the input, the function attached to the input’s “change” event updates state.input (which then adjusts the value and so on)
i think this is so your page code handles the data, otherwise its only your browser that does it. You want your code to handle the data so you are able to better modify and control it and not rely on browser built in functions. It might be confusing at this stage for you and it certainly was for me, but in the long run know this is the right way to handle it and you should stick to it.
React needs to control what the value of it is. So you need to be able to set what the value is, and provide a way to update it via a function.
So you attach the value to the state, then update the state via onChange (or a similar event handler). This is a controlled component
You can leave it off, but then you need a way for React to access the HTML it generates so it can read the value from it: this is an uncontrolled component, and it’s not as simple to work with most of the time