I am new to ReactJs. I am trying to achieve onClick functionality on a button to change the text between <h1> tag.
Here is the code
class MessageStateComponent extends Component{
constructor(){
super()
this.state = {
message: 'Subscribe to NewsLetter'
}
}
changeMessage(){
this.setState({
message: 'Thank You'
})
}
render(){
return (
<div>
<h1>{this.state.message}</h1>
<button onClick = {this.changeMessage}>Subscribe</button>
</div>
)
}
}
export default MessageStateComponent
On clicking the button I am getting this error in the console
TypeError: Cannot read property 'setState' of undefined
changeMessage src/components/MessageStateComponent.js:30
27 | 28 | changeMessage(){ 29 |30 | this.setState({
| ^ 31 | message: 'Thank You' 32 | }) 33 |
EDIT: When I change
<button onClick = {this.changeMessage}>Subscribe</button>
to
<button onClick = {this.changeMessage()}>Subscribe</button>
I am getting this error:
Error: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.