0

How can I add/ remove a className on click to change the style of some component?

enter image description here

  • I want to rotate the arrow on the right when I click on it and display: none; all the components beside it.

  • I also want to add do the same thing when I hit the mobile breakpoint

Mahmoud Ali
  • 116
  • 2
  • 2
  • 10

2 Answers2

3
const [isRotated, setIsRotated] = useState(false);

handleClick() {
 setIsRotated(true)
}

<button className={isRotated && 'rotate-class'} onClick={handleClick} />
{ !isRotated && <Element/>} // this will hide the element when clicked on the button

This would a better approach then setting display: none on the other elements, but if you must do that, do this:

 <Element style={{ display: isRotated ? 'none': 'block' }} /> // I'm guessing the default style of display is 'block' of the elements you want to hide
Mohaimin
  • 664
  • 4
  • 10
2

You can add boolean state and function for change state same this code.

function App() {
  const [state, setState] = useState(true);

  const rotateHandler = () => {
    setState(() => !state);
  };

  return (
    <div className="App">
      {/* button for change state */}
      <button onClick={rotateHandler}>click for rotate and hide</button>
      {/* icon for rotate */}
      <div>
        <FontAwesomeIcon
          icon={faAngleRight}
          style={{
            transform: state ? "rotate(90deg)" : "rotate(0deg)"
          }}
        />
      </div>
      {/* text hide when */}
      <div style={{ display: state ? " block" : "none" }}>
        <div>text hide after state is false</div>
        <div>you can click on button</div>
        <div>for rotate arrow icon</div>
        <div>and hide this text</div>
      </div>
    </div>
  );
}

I add conditions in inline style, but you can add conditions on className

className={state ? "show" : "hide"}