DidemDR
DidemDR

Reputation: 37

Creating controlled input in react

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..

Upvotes: 2

Views: 1077

Answers (3)

Andrew Zheng
Andrew Zheng

Reputation: 2858

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.

Upvotes: 3

Jamie Fisher
Jamie Fisher

Reputation: 31

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

onChange={this.handleChange}

Upvotes: 1

xehpuk
xehpuk

Reputation: 8241

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

Upvotes: 1

Related Questions