1

I am currently trying to display several buttons based on array values. Out of those buttons, one will have a different className to the others and I want to switch this className to the button that's clicked.

In my codesandbox example, "John" has className value of "one". I want to be able to click on another button, giving it the className of "one" and giving John (or any other element that had the initial className of one) className="two"

Here's a codesandbox, hopefully that makes more sense.

2 Answers 2

2

If you mean you want the button you click on to turn red, here is a codesandbox with this functionality added:

https://codesandbox.io/s/frosty-herschel-l87wx

Sign up to request clarification or add additional context in comments.

Comments

0

create a state:

const [activeName, setActiveName] = useState("");

then when someone CLICK the element put onClick event:

onClick={() => setActiveName("invest")}

Now set up a Class Rule, if activeName === 'invest' && 'classYouWantToApply'

like this:

<div className={`${activeName === "invest" && "active"}`}>Invest</div>

So here if my State matches the 'invest' which is the name of the element, then class 'active' applies, if the state does NOT match, then nothing happens.

This way ONLY 1 element that matches the state will have applied class, the rest will not.

I am assuming you are doing this for a NAV BAR, so that when user clicks a NAV Element, it lights up, so user can see in Which Nav Element he is browsing. So this is the solution.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.