2

I'm a newbie and learning React with FreeCodeCamp. On this challenge it says:

When you type in the input box, that text is processed by the handleChange() method, set as the input property in the local state, and rendered as the value in the input box on the page. The component state is the single source of truth regarding the input data.

I wrote this solution:

 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>
  );
}
};

the console says:

“Build error, open your browser console to learn more.”

Where am I doing wrong? I cannot see my mistake..

3 Answers 3

3

The issue is related to how you assign the event handler to onChange.

onChange expects a callback function which will be fired when value of the input is changed. With onChange={this.handleChange()} in your post, you actually assigns undefined to onChange since handleChange function update the component state but it doesn't return anything.

Change it to onChange={this.handleChange} does what you expect it to work. When input is changed, this.handleChange will be called and event object will be passed in as parameter.

Hopefully that helps.

Sign up to request clarification or add additional context in comments.

1 Comment

That's not true. It doesn't assign undefined, it throws because event is undefined.
1

You're calling handleChange instead of passing its reference as the onChange prop.

Comments

1

You likely do not need to run your handleChange method in the onChange prop. So you would have this instead:

onChange={this.handleChange}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.