User199932
User199932

Reputation: 86

Remove and change className onClick for multiple elements simultaneously - ReactJS

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.

Upvotes: 1

Views: 820

Answers (2)

fruitloaf
fruitloaf

Reputation: 2892

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.

Upvotes: 0

Matt
Matt

Reputation: 1188

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

Upvotes: 2

Related Questions