Karan Rajput
Karan Rajput

Reputation: 75

How to add classes in ReactJs dynamically?

I want one class to be toggled on onClick, the functionality that i want is whenever i click on the one of the icon it's color should get changed, (default color will be same for the both the icons but whenever I click one of the icons a class will be added and according to that class color should get changed and when I click again that class should get removed.)

import "./App.css";
import { BsCloudRain } from "react-icons/bs";
import { GiForest } from "react-icons/gi";

function App() {

  return (
      <div id="container">
        <div id="icons">
          <BsCloudRain className="rain" />
          <GiForest className="forest" />
        </div>
      </div>
  );
}

export default App;

Upvotes: 0

Views: 1368

Answers (2)

PsiKai
PsiKai

Reputation: 1978

Add an onClick handler to your icon components. Then create a function that takes the event target and accesses the classList to toggle the class you want to add. This will remove the class when clicked again, if it's already on the list.

import "./App.css";
import { BsCloudRain } from "react-icons/bs";
import { GiForest } from "react-icons/gi";

function App() {
  const toggleClass = (e) => {
    e.target.classList.toggle("green")
  }

  return (
      <div id="container">
        <div id="icons">
          <BsCloudRain className="rain" onClick={toggleClass}/>
          <GiForest className="forest" onClick={toggleClass} />
        </div>
      </div>
  );
}

export default App;

Upvotes: 1

ruakh
ruakh

Reputation: 183574

The className property, despite the name, isn't necessarily one class-name: it can be zero, one, or more class-names, separated by spaces. So if you have a boolean shouldIncludeRainClass, then you can write

<BsCloudRain className={shouldIncludeRainClass ? 'rain' : ''} />

to get className='rain' when the boolean is true and className='' (meaning "no class") when it's false.

Upvotes: 0

Related Questions