0

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;
1
  • React.useState Commented Jul 3, 2022 at 4:18

2 Answers 2

1

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;
Sign up to request clarification or add additional context in comments.

Comments

0

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.

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.