I am a beginner in react.js, I am trying to implement a simple fizzbuzz example. Overall, I think I got the gist of how react and its components work, but when I try to run this code on codepen, I get this error:
maximum call stack size exceeded
Here is my code:
class App extends React.Component {
constructor(props){
super(props);
this.state = {
value : '',
number: 0
};
this.handleIncrement = this.handleIncrement.bind(this);
this.handleDecrement = this.handleDecrement.bind(this);
this.fizzBuzz = this.fizzBuzz.bind(this);
}
fizzBuzz(nb){
if(nb % 15 == 0 && nb!= 0)
this.setState({value : `FizzBuzz `});
else if(nb % 5 == 0 && nb!= 0)
this.setState({value : `Buzz `});
else if(nb % 3 == 0 && nb!= 0)
this.setState({value : `Fizz `});
else
this.setState({value : ''});
}
handleIncrement() {
let nb = this.state.number + 1;
this.setState({number: nb});
this.fizzBuzz(nb);
}
handleDecrement() {
let nb = this.state.number-1;
if(nb >= 0)
{ this.setState({number: nb});
this.fizzBuzz(nb);
}
else
{
this.setState({number: 0});
}
}
render() {
return (
<div>
<h1> {this.state.number} </h1>
<h1> {this.state.value} </h1>
<input type="button" value="add" onClick={this.handleIncrement()} />
<input type="button" value="sub" onClick={this.handleDecrement()} />
</div>
);
}
}
ReactDOM.render(<App/>,document.getElementById('app'));
anyone could point out what mistake i did please ? it's been puzzling me for the last two hours.
best regards
this.handleIncrement()should bethis.handleIncrement, I think you're constantly rerending the component because of thisthis.handleIncrement()andthis.handleDecrement()in therendermethod.this.handleIncrement()and assigning the return value toonClick. Butthis.handleIncrement()doesn't return anything. I assume you want to bindthis.handleIncrementas event handler itself. As such you have to assign it toonClick, not its return value, i.e. don't call the function, pass it.