Hi,
I have already solved this exercise but I have a problem. Originally, I did it this way but it does not work. Then I was looking for help and tried another way and it worked, but for me, both are the same.
The part that changes is the submitMessage function.
This is the way I put it first:
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){
let newVal = event.target.value;
this.setState({input: newVal})
};
submitMessage(){
let newMessage = this.state.messages;
newMessage.push(this.state.input);
this.setState({messages: newMessage,
input:''})
}
render() {
return (
<div>
<h2>Type in a new Message:</h2>
{ /* render an input, button, and ul here */ }
<input value={this.state.input} onChange={this.handleChange}/>
<button onClick={this.submitMessage}>Add message</button>
<ul>
</ul>
{this.state.messages.map(message=><li>{message}</li>) }
</div>
);
}
};
And this is the code that passes the test:
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){
let newVal = event.target.value;
this.setState({input: newVal})
};
submitMessage(){
let newMessage = [...this.state.messages, this.state.input];
this.setState({messages: newMessage,
input:''})
}
render() {
return (
<div>
<h2>Type in a new Message:</h2>
{ /* render an input, button, and ul here */ }
<input value={this.state.input} onChange={this.handleChange}/>
<button onClick={this.submitMessage}>Add message</button>
<ul>
</ul>
{this.state.messages.map(message=><li>{message}</li>) }
</div>
);
}
};
https://learn.freecodecamp.org/front-end-libraries/react-and-redux/manage-state-locally-first