React - Create a Controlled Form

Tell us what’s happening:

Why are we using 2 properties “input” and “submit” in the state as opposed to just “value” or just “input”?

If we are truly doing a form I guess we would do it with just 1 as shown in the reactjs page?

My point is that when the user submits, we just need one single value with it.

I guess it was to make it clear that we can collect what the user submits? Not sure it really does it.
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(state => ({ submit: 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 (X11; Linux x86_64; rv:104.0) Gecko/20100101 Firefox/104.0

Challenge: React - Create a Controlled Form

Link to the challenge:

I might be wrong, but I think the challenge at one point may have asked for the input to be cleared after the submission. I can’t tell looking at the challenge git history, but the hint page history suggests as much.

It might also make the controlled element part clearer by having different state properties. It also splits it up into two handlers, one for the controlled element change handle and one for the submit handle. This is a pretty common way of doing it even today with hooks, change state for each input, and a submit handler.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.