It doesn’t work because you’ve made a series of errors. One extremely visible error appears immediately when you try to run that code, when it tells you that there isn’t a method called onChange. The method, the one you have written, is called handleChange. There are a series of other errors, I’ve commented each one.
Also, the reason the ``` doesn’t work is because you added an extra line of them: anything inbetween two lines of ``` is treated as a code block. I’ve removed the extra line and the spoiler tags from your post
class DisplayMessages extends React.Component {
constructor(props) {
super(props);
this.state = {
input: '',
messages: []
}
}
handleChange(event){
// setState IS A FUNCTION.
// this.setState({ input: SOME_NEW_VALUE })
this.setState={
input: event.target.value,
messages: this.state.messages
};
}
submitMessage(){
// setState IS A FUNCTION.
// this.setState({ input: SOME_NEW_VALUE })
this.setState=({
input: '',
messages: [...this.state.messages, this.state.input]
});
}
render() {
return (
<div>
<h2>Type in a new Message:</h2>
<input
// NO METHOD CALLED onChange, IT'S
// SUPPOSED TO BE handleChange
onChange= {this.onChange.bind(this)}
// NO PROPERTY ON OBJECT CALLED messages,
// IT'S SUPPOSED TO BE this.state.input
value={this.messages.input}
/>
<button onClick ={this.submitMessage.bind(this)}>Submit</button>
<ul>
{
this.state.messages.map((x,i) => {
return <li key={i}>{x}</li>
})
}
</ul>
} // EXTRA BRACKET
} // EXTRA BRACKET
</div>
);
}
};
I would suggest taking a step back, then come back to it. Maybe work on, or learn, something else for a bit. I’d also suggest using other resources to learn React, there are a ton of resources. Here is the fCC React Tutorials playlist.
React can be pretty overwhelming at first. However, having a solid JS foundation will really help you. Some of the errors pointed out would be reasonably “debuggable” to someone with no React knowledge but a strong JS foundation. It also just makes learning React much easier and understandable. I’d suggest plugging away at some more plain JS learning to help give you a stronger foundation to build on.
Here is a stupid analogy for you. It doesn’t matter how fancy the penthouse on the top floor is, if the foundation is garbage the building will fall.