I have multiple buttons in which i want only 1 selectable, when i click over one of these buttons, an active class gets added to it, while the other buttons active classes gets removed. I am actually using next js and i am fairly new to it.
return (
<div className="flex py-24 bg-hebdo w-full">
<div className="flex flex-col gap-5 justify-center items-center w-full">
<h2>HEBDO</h2>
<div className="flex items-center justify-between gap-2 border flex-grow">
<button className={`py-1.5 px-2 rounded-[3px] text-orange-white-light bg-[#ffffff40] ${active ? 'active' : ''}`} onClick={clickActivate}>
<DayItem />
</button>
<button className={`py-1.5 px-2 rounded-[3px] text-orange-white-light bg-[#ffffff40] ${active ? 'active' : ''}`} onClick={clickActivate}>
<DayItem />
</button>
</div>
</div>
</div>
);
here is my react component, i usually use querySelectorAll to remove all classes and keep only the one i want, but in next js i think its not good to use it basic javascript while we have react hook ‘useState’.
thank you in advance
2
Answers
Yes you can use UseState. In clickActivate method , you can set the activeButton state.
To achieve this, you need to manage the state of the ‘active’ button and update it when a new button is clicked. Here is a step-by-step approach to solve this problem:
keep track of the currently active button. You can use the useState
hook from React for this. The initial state will be null as no
button is active when the component first renders.
Here is the final code:
As you can see, this solution uses a state variable to keep track of the active button and updates the state when a button is clicked. When rendering, it checks if the current button index matches the active button state and adds the ‘active’ class accordingly