React question(create a controlled input)

Hello all !
I’m wondering about this exercise : the create a controlled input , in react?
I completed it and submitted and it passed just fine, but when I enter the same code in a react fiddle (just to play around with the code more) it didn’t ?

I get some error: Uncaught typeError: cannot read the property ‘value’ of null.

Here’s the code (I added a ReactDOM.render() function just to see the results).
in the fiddle there is html code with an

and id of containerinput.
class ControlledInput extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      input: ''
    };
    this.handleChange = this.handleChange.bind(this)
  }
  handleChange(event){
    this.setState((state) => ({
        input : event.target.value
    }));
  }
  render() {
    return (
      <div>
        <input value={this.state.input} onChange={this.handleChange}/>
        <h4>Controlled Input:</h4>
        <p>{this.state.input}</p>
      </div>
    );
  }
};
ReactDOM.render(<ControlledInput/>,document.getElementById("containerinput"));

Thanks :slight_smile:

Hello there,

It would be beneficial to see your Fiddle…

If I took a guess, I would say it has something to do with the use of the anonymous arrow function as the callback:

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

Try changing to this:

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

Hope this helps

Thanks! Now it works :grin: Does it have something to do with scope?
I vaguely remember reading something like that , that arrow functions don’t contain event bubbling or such :stuck_out_tongue:

It has to do with how setState (the callback) and events in React works.