How to efficiently toggle classes with multiple HTML elements across multiple files

I am toggling an arrow image whenever my div is clicked. I am controlling the state of the click with

const [toggleArrow, setToggleArrow] = useState(false)

My div has an onClick function that controls the state and toggles the faq-subject-toggle-arrow class that adds an image

<div className={`faq-subject ${toggleArrow ? 'faq-subject-toggle-arrow' : ''}`} onClick={() => {
  setToggleArrow(!toggleArrow)
}>

My problem is that I have 50 divs across multiple styles and don’t want to make 50 states to toggle one image.

Is there a more efficient solution for this with less code?

6 thoughts on “How to efficiently toggle classes with multiple HTML elements across multiple files”

  1. I created something that does the same thing. I extracted your code and made a component. now the state lives inside the component and will not affect others.

    live demo

    component

    import { useState } from "react";
    
    export const Button = () => {
      const [toggleArrow, setToggleArrow] = useState(false);
      return (
        <div
          style={{ width: "50px", height: "50px", margin: "10px" }}
          className={`faq-subject ${toggleArrow ? "faq-subject-toggle-arrow" : ""}`}
          onClick={() => {
            setToggleArrow(!toggleArrow);
          }}
        ></div>
      );
    };
    

    css file, I didn’t have the same classes so I created mine.

    .faq-subject {
      background: blue;
    }
    .faq-subject-toggle-arrow {
      background: orange;
    }
    

    now you can use it wherever you want for multiple times

    import { Button } from "./button";
    import "./styles.css";
    
    export default function App() {
      return (
        <div className="App">
          <Button />
          <Button />
          <Button />
          <Button />
          <Button />
        </div>
      );
    }
    
    Reply

Leave a Comment