Reputation:
I try to add and remove class on three buttons. When I click, a class should be add and remove on others buttons.
I have a const:
const [genderActive, setGenderActive] = useState('');
const isGenderActive = (active) => {
setGenderActive(active);
};
the HTML:
<div aria-label="title" role="group" class="btn-group">
<button name="0" type="button" className={genderActive === 0 ? 'selected btn btn-primary' : 'btn btn-primary' } onClick={isGenderActive(0)}>M.</button>
<button name="1" type="button" className={genderActive === 1 ? 'selected btn btn-primary' : 'btn btn-primary' } onClick={isGenderActive(1)}>Mme.</button>
<button name="2" type="button" className={genderActive === 2 ? 'selected btn btn-primary' : 'btn btn-primary' } onClick={isGenderActive(2)}>Mx</button>
</div>
When I compile the react I have an error:
Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.
I have find multiple post with this error but I can't solve the problem.
Do you how I can solve this one ?
Upvotes: 0
Views: 33
Reputation: 12787
Because you call isGenderActive
on render. So state change and re-render. You just update to make sure isGenderActive
only call when click:
onClick={() => isGenderActive(0)}
Upvotes: 1