Create a Controlled Input help

Tell us what’s happening:
Hello campers, I need help solving this Challenge, I´m stuck right now!

Your code so far


class ControlledInput extends React.Component {
constructor(props) {
  super(props);
  this.state = {
    input: ''
  };
  // Change code below this line
handleChange(event) {
  this.setState({
    input: event.target.value
  });
}
  // Change code above this line
}
// Change code below this line
<input onChange = {this.handleChange.bind(this)}/>
// Change code above this line
render() {
  return (
    <div>
      { /* Change code below this line */}
<input value = {this.state.input}/>
      { /* Change code above this line */}
      <h4>Controlled Input:</h4>
      <p>{this.state.input}</p>
    </div>
  );
}
};

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36.

Challenge: Create a Controlled Input

Link to the challenge:

You’re almost there, it’s just that some things are in the wrong places.

So, the comments show three sections to makes changes.

In the first one (in the constructor) you have defined your handleChange - but this is where it wants you to bind this. The format would be this.myMethod = this.myMethod.bind(this);

In the second one (in the class body) you have an input element - that doesn’t go there - that should be where you define your handleChange method.

In the last comment section (in the JSX), you have your input element - good, that goes there. But it needs the onChange attribute. In the other version of the input, you bind this. Yes, that works, but the more common way is to do this in the constructor to avoid clogging up the code. (Actually, with arrow functions, most people don’t even bother with this, but that’s cool for now.) So you would just need to pass the method.

When I make those changes, it works. And don’t get stressed - React is weird until you get used to it.

1 Like

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