Tell us what’s happening:
Here in the code
this.setState({
submit: this.state.input
});
we use this.state.input to assign value to submit .
It was mentioned in the previous lesson “Use State to Toggle an Element” to not use this inside setState.
Instead use
this.setState(state => ({
counter: state.counter + 1
}));
in a previous exercise toggle visibility we were told to use state.visibility.
So i would like to know the reason why we are using this.state.input.
would state.input work same here…
Your code so far
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>
);
}
};
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36
Challenge Information:
React - Create a Controlled Form