Hi all.
I’m wondering why my solution to the freecodecamp challenge is wrong?
This is my solution , the result is that it appends to the list each time the user clicks the button.
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);
}
handleChange(event) {
this.setState ({
input : event.target.value,
})
}
submitMessage(){
const itemsArray = this.state.input.split('');
if(this.state.messages){
this.setState({
messages: [...this.state.messages,itemsArray],
input: ''
})
}else {
this.setState({
messages: itemsArray,
input: ''
})
}
}
render() {
return (
<div>
<h2>Type in a new Message:</h2>
<input value={this.state.input} onChange={this.handleChange}/>
<button onClick={this.submitMessage}>Add message</button>
<ul>
{ this.state.messages.map(function(item,index) {
return <li>{item}</li>
})}
</ul>
</div>
);
}
};
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36
.
Challenge: Manage State Locally First
Link to the challenge:
Here is the freecodecamp solution: the results with testing this look the same , it appends the new text to the end of the list each time the user clicks the button. So I’m unsure why my code is wrong?
class DisplayMessages extends React.Component {
constructor(props) {
super(props);
this.state = {
input: '',
messages: []
}
}
// add handleChange() and submitMessage() methods here
handleChange(event){
this.setState({
input: event.target.value,
messages: this.state.messages
})
}
submitMessage(){
this.setState({
input: '',
messages: [...this.state.messages, this.state.input]
})
}
render() {
return (
<div>
<h2>Type in a new Message:</h2>
{ /* render an input, button, and ul here */ }
<input onChange={this.handleChange.bind(this)} value={this.state.input}/>
<button onClick={this.submitMessage.bind(this)}>Submit</button>
<ul>
{this.state.messages.map((x, i)=>{
return <li key={i}>{x}</li>
})}
</ul>
{ /* change code above this line */ }
</div>
);
}
};
ReactDOM.render(<DisplayMessages/>,document.getElementById("container"));
All the tests pass , except for this one: Clicking the Add message
button should call the method submitMessage
which should add the current input
to the messages
array in state
Thanks