React: Create a Controlled Input - weird code

Hello,

My code below does not work - but it passes the test !? Need some help please

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 - probably some issue here but why ?
handleChange(event){
  this.setState(state => ({
    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}></input>
        { /* change code above this line */}
        <h4>Controlled Input:</h4>
        <p>{this.state.input}</p>
      </div>
    );
  }
};

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

Welcome, pascal.

If you open your devTools, you will see this error:
image

This is where you have your issue:

this.setState(state => ({
    input: event.target.value
  }))

To give more information on the error: Someone can correct me on this if I am wrong…

  • The passed event is attached to the function. So, using another function to set the state with event used within it, is kind-of like asking for the event of the setState callback, and not the onChange => handleChange callback.

Essentially, if you want to use the method above, you need to do something like:

handleChange(event){
  const myEvent = event.target.value;
  this.setState(()=>({input: myEvent}))
}

I have moved this to a more suitable subforum.

Hope this helps

Unless you need the current state you shouldn’t use an updater function. Using an updater function is problematic with event handling because of how React deals with events.

More info with some links:


Edit: I guess it would be nice if the challenge failed but I’m not sure what changes that would take or if it’s feasible.