I keep getting the following error message when I run an inline onClick method:
inputDigit(digit){
this.setState({
displayValue: String(digit)
})
<button type="button"onClick={this.inputDigit(0)}>0</button>
Error message:
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.
However, the error disappears when I call the method using an arrow function:
<button type="button"onClick={() => this.inputDigit(1)}>1</button>
Why is that?
The function onDigit sets the state, which causes a rerender, which causes onDigit to fire because that’s the value you’re setting as onClick which causes the state to be set which causes a rerender, which causes onDigit to fire because that’s the value you’re… Etc
I haven’t really played with React much. is onClick
really good practice in React?
My instinct would be to use element.addEventListener("click", handler);
and leave the html dumb.
Ah, if you aren’t familiar with React then it would look a bit wierd, but basically what you say is what it’s actually doing. It’s not a inline handler because that isn’t HTML, it’s a JS object written in a syntax that looks like HTML
1 Like
In React you write everything in JS (except css) so writing handlers and functions in each component is common.
1 Like