Reputation: 3044
I have a simple component with a small state. I want a button on click to change that state to something else. Right now I am seeing an unexpected token error and don't quite understand why.
Below is the code:
// Component to practice simple state mgmt
import React from 'react'
class Stateful extends React.Component{
state = {
flag: true,
text: "I am simple text"
}
render() {
return(
<div>
<h2>Small State example</h2>
<p>{this.state.text}</p>
<button onClick={
this.setState(
prevState=>({
flag: !prevState.flag,
text: prevState.text.toUpperCase()
})
}>Click to change state</button>
</div>
)
}
}
export default Stateful
Upvotes: 0
Views: 66
Reputation: 17608
You are missing one )
in your onClick function and you are not using it right. You need to use a function and invoke it for onclick event like this () => ...
render() {
return (
<div>
<h2>Small State example</h2>
<p>{this.state.text}</p>
<button onClick={ () =>
this.setState(
prevState=>({
flag: !prevState.flag,
text: prevState.text.toUpperCase()
}))
}>Click to change state</button>
</div>
)
}
I also prefer extracting onClick handler to a separate function. So our render method will be cleaner with this way.
handleClick = () =>
this.setState(
prevState => ({
flag: !prevState.flag,
text: prevState.text.toUpperCase()
}))
render() {
return (
<div>
<h2>Small State example</h2>
<p>{this.state.text}</p>
<button onClick={this.handleClick}>Click to change state</button>
</div>
)
}
Upvotes: 1
Reputation: 195982
You are not assigning a handler for the click event. You are directly calling setState
which is bad because you are in the render
method and a state change causes a re-render, effectively creating an infinite loop.
You are also missing a )
So use
<button onClick={()=>
this.setState(
prevState=>({
flag: !prevState.flag,
text: prevState.text.toUpperCase()
}))
}>Click to change state</button>
Working demo at https://codesandbox.io/s/j2x9jm38y5
Upvotes: 2