React - Create a Controlled Input

Tell us what’s happening:
The only test that isn’t passing is the one that says Typing in the input element should update the state and the value of the input, and the p element should render this state as you type. The reality is that my code should be passing this test. Without modifying my code, type in the input and you’ll see the state updates and the input value displays in the p element.

  **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(){
        this.setState({
          input: document.querySelector('input').value
        })
      }
// Change code above this line
render() {
  return (
    <div>
      { /* Change code below this line */}
          <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 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36

Challenge: React - Create a Controlled Input

Link to the challenge:

1 Like

We need this bit yet:

Set the value property for the input element.

Also, another way to use the input in the handleChange is this:

     handleChange(e){
        this.setState({
          input: e.target.value
        })

Which does not need to search in the document tree, as you are basically passing the element object representation.

Edit:

You set the value because the form will be sent at some point, that is the bit that should be grabbed when sending it to the server. Not saying it is the best way, but that seems to be the thing here.

1 Like

My handleChange method is this way now but is still failing the same test:

        handleChange(e){
          this.setState({
            input: e.target.value
          })
        }
1 Like

That was only a suggestion. What really makes trouble is that they expect:

<input value={something!!} onChange = {handleOnChange}/>

Now if you read the code with care, you are doing this:

  1. Gathering the current value
  2. Changing the state which triggers a re-render
  3. Re-setting the value

I presume this is because the re-render would remove the previous value, and what I wrote before as well, but honestly I am not fully sure.

1 Like

Thank you for your help mahneh. I set the input value to the state property as you suggested.

1 Like

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