We're trying to add a onChange
handler to one of our custom components - namely, a Checkbox
component (the only reason for it being a custom component is so that we can efficiently encapsulate the intermediate
HTML attribute). It looks something like this:
<Checkbox
id="select-all"
onChange={this.handleSelectAllChange(ids)}
indeterminate={isIndeterminate}
checked={areVisibleItemsSelected}
disabled={isDisabled}
/>
The handler function is structured somewhat like this:
handleSelectAllChange(ids) {
// omitted code that filters on ids and produces newIds
this.props.updateIds(newIds);
}
Where this.props.updateIds
is a passed-down function that modifies the parent component's state.
The problem is that this function is called about 10 times during page load, which is not intended. I thought it was only called when the actual checkbox element is modified?
Its because your app component is a wrap in StrictMode . It is expected that setState updaters will run twice in strict mode in development. This helps ensure the code doesn't rely on them running a single time (which wouldn't be the case if an async render was aborted and later restarted).
Your useEffect is executed only once per render cycle, but you have several state updates in your useEffect which cause a re-render. Hence you get a lot of alerts. useEffect executes on every re-render if you don't pass the dependency array.
How to use handleChange() function in react component? An onChange event is triggered when values are entered in the input. This fires a function handleChange(), that is used to set a new state for the input.
By declaring it like this onChange={this.handleSelectAllChange(ids)}
the method call happens immediately at rendering the CheckBox
. With ES6 you can avoid this by using
onChange={() => this.handleSelectAllChange(ids)}
This means you pass a new function which will call handleSelectAllChange
on change.
I just had the same issue... I was able to fix the problem stopping the propagation of the event. Add this in the function being called by your onChange event:
e.stopPropagation();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With