Simple thing, I'm supposed to make a counter app that increments/decrcements/resets a counter if I click on the corresponding button (up/down/reset).
I'm new to React but know some js.
I get this as error message
Warning: Expected `onClick` listener to be a function, instead got a value of `string` type.
in button (created by App)
in div (created by App)
in div (created by App)
in App
<script type=text/babel>
class App extends React.Component {
constructor(props) {
super(props)
this.state = {count: 0} // init count
}
render() {
return <div className="counter">
<div className="title">Counter</div>
<div className="number">{this.state.count}</div>
<div className="buttons">
<button onClick='incrementCounter()'>Up</button>
<button onClick='decrementCounter()'>Down</button>
<button onClick='resetCounter()'>Reset</button>
</div>
</div>
}
// why does this not work?
incrementCounter(){
this.setState( state => ({ count: this.state.count + 1 }) )
}
decrementCounter(){
this.setState( state => ({ count: this.state.count - 1 }) )
}
resetCounter(){
this.setState( state => ({ count: 0 }) )
}
}
ReactDOM.render(<App/>, document.getElementById("root"))
</script>
What am I doing wrong?
onClick='incrementCounter()'
needs to be onClick={this.incrementCounter}
, and similar for the other onClick's In JSX, you want to surround Javascript code with curly braces and for attributes, you omit the quotes to use curly brances.
Each onClick attribute should be surrounded by braces instead of quotes:
<button onClick={incrementCounter}>Up</button>
incrementCounter
in render. You're also overlooking that the OP's component is a class component. this
will not reference the correct object. incrementCounter
in scope