Input element should render the value of input in local state. What does that means?

Tell us what’s happening:

Your code so far


class DisplayMessages extends React.Component {
constructor(props) {
  super(props);
  this.state = {
    input: '',
    messages: []
  }

  this.handleChange = this.handleChange.bind(this);
  this.submitMessage = this.submitMessage.bind(this);
}
// add handleChange() and submitMessage() methods here
handleChange(event){
return this.setState({input:event.target.value})
  }
submitMessage(){
 this.setState({messages: [this.state.input],input: ''})

}

render() {
  return (
    <div>
      <h2>Type in a new Message:</h2>
      <input onChange={this.handleChange} type="text"/>
      <button onClick={this.submitMessage}>Add message</button>
      <ul>
        {this.state.messages.map(item =>{
          return <li>item</li>
        })}
      </ul>
       

      { /* change code above this line */ }
    </div>
  );
}
};

Your browser information:

User Agent is: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:72.0) Gecko/20100101 Firefox/72.0.

Challenge: Manage State Locally First

Link to the challenge:
https://www.freecodecamp.org/learn/front-end-libraries/react-and-redux/manage-state-locally-first

OK, you have a couple of small problems here. First of all, the problem at hand - your input is being saved to state, the problem with that your input isn’t rendering what is in state. The input is not given a “value” so it just works on it’s own. But you want it to be wired directly to this.state.input, is the input isn’t controlling what it displays but it’s output is wired to state. This may seem unimportant now, but trust me, it is an important distinction. So, in:

<input onChange={this.handleChange} type="text"/>

you need to give it a value prop:

<input onChange={this.handleChange} type="text" value={this.state.whateverIWantItToShow} />

Is that enough of a hint?

I’ll give you hints for your other problems:

submitMessage(){
 this.setState({ messages: [this.state.input], input: ''})
}

You are overwriting the value of messages with just input. Instead, you want to append that value to the array.

And…

 return <li>item</li>

There is a problem here. You’re just going to create list elements of the string “item”. You want to display the variable item there. How do you get JSX to show a JS variable?

When I make those three changes, your code passes for me.

2 Likes

Thank you so much Kevin!