Learn React: Create a Controlled Input; Tests passing when they shouldn't

Learn React: Create a Controlled Input

This challenge is able to be passed with:

handleChange(event) {
    
    this.setState(function(state) {
      return {input: event.target.value}})
  }

But the above code does not result in the form element functioning correctly. The html disappears from the preview panel and errors are thrown in the console. (I don’t fully understand why “event” doesn’t seem accessible in the nested function, but this isn’t a curriculum help request.)

But the proper solution actually uses something like:

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

I’m confused, why the following code doesn’t work:

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

Although we learned it in a previous challenge, I understand this should be used to capture state and props, however why the form doesn’t work with it? And yes I tried it and the tests passed! Although the html not working and I’m getting errors in the console as you said, I need to understand.

I’ve just tried the following:

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

And everything is working now!

I created the following new topic to understand better:

I think it is something to do with what this article explains: " React recycles events objects for performance reasons"

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