'this' problem related to React “Create a Controlled Form” Challenge

In the following code:
Why do we need to add this.state to input but not to submit, does it have to do with the event object passed to the handleSubmit function?

handleSubmit(event) {
  // change code below this line
  event.preventDefault()
 
  this.setState({
    submit: this.state.input
 
  })
  // change code above this line
}

Complete code for the challenge

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>
  );
}
};

When you call the method “this.setState({})” you already call the React Object by saying “this” and the sets its state. If you notice, you pass in an object (That’s why you use curly brackets). An object contains key-value pairs, and in this case your key is “submit” (which is nothing but a name) with the value that you grab.

To grab the value you call “this.state.input” which means that you checks the state of the object “this” (the React Object) - and then grabs the input value which is another key-value pair. In the handleChange(event) {} function/method, you assign the key “input” with the value “event.target.value”. That means your React Object has a state that contains the following:

{
  input: event.target.value
  submit: this.state.input
}

Whenever the input field changes, it updates the “input” value in the Object state. When you click “Submit!”, it will then copy this value into the Object state key “submit”.
I hope that makes sense? :slight_smile:

1 Like

thanks! it all makes sense now

1 Like

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