Create a Controlled Input - The Coding Logic

Tell us what’s happening:
After carefully reading the instructions I found the solution but am still a bit confused on the logic behind the coding.

When I type in the UI text field:

  • the event handler onChange triggers the class method handleChange()
  • handleChange() updates the component state property input
  • and the

    element inherits the updated input property

The part where I’m confused is the input text field on the UI. The exercise states that the ’ The component state is the single source of truth regarding the input data’.

Every time I type in the text field the component state is updated. Is the input field inheriting from the component state? It all seems a bit circular.

Your code so far


class ControlledInput extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      input: ''
    };
    // change code below this line
this.handleChange = this.handleChange.bind(this)
    // change code above this line
  }
  // change code below this line
handleChange(event){
  this.setState({input: event.target.value})
}
  // change code above this line
  render() {
    return (
      <div>
        { /* change code below this line */}
<input value = {this.state.input} onChange = {this.handleChange} />
        { /* change code above this line */}
        <h4>Controlled Input:</h4>
        <p>{this.state.input}</p>
      </div>
    );
  }
};

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/front-end-libraries/react/create-a-controlled-input/

You say you’re confused, but your explanation is right on. Yes, it’s a little weird to think about. Maybe there is one thing you are not getting (in bold).

  • The state has a text value, say “foo”.
  • The component sees this.state.input so it shows its contents in the field.
  • To type the “d” key.
  • The field on the screen does nothing because it is being controlled by this.state.input.
  • The onChange fires, updating state.
  • In response to the change in state, the component rerenders and the new value of this.state.input shows up in the field.

Your typing does not change what is in that field directly, That is a “controlled input” meaning that all it cares about is this.state.input. Period. The only way to change that input is to change this.state.input. You should be able to test this. Comment out the setState statement in the handleChange method. No typing should change what happens in the input field because all it cares about is this.state.input. The only way to change it is to change state - the “single source of truth.”

Thanks for the clarification. You explained exactly what I thought was going on but unable to articulate clearly.