Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

71
Views
React toggle active class between button group array

I made a photo gallery with a filter for categories, but I want to make the active category button to have the active class

I display the buttons by mapping through the galleryData array

{
  galleryData.map((item, index) => (
    <button
      key={index}
      onClick={() => filterGalley(item.category)}
      className="filter-button"
    >
      {item.category}
    </button>
  ));
}

And onClick I filter the gallery items by category. The value is a string of category type

const filterGalley = (value) => {
  if (value === "all") {
    setGalleryItems(galleryData);
    return;
  }

  const filteredData = galleryData.filter((item) => item.category === value);

  console.log(value);
  setGalleryItems(filteredData);
};

How can I pass the active class to the currently viewed category? onMount should be all and after that the one that's clicked.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Define a state for activeCategory and use it for active class:

const [activeCategory, setActiveCategory] = useState('all');
const filterGalley = (value) => {
    setActiveCategory(value);
    if (value === 'all') {
        setGalleryItems(galleryData);
        return;
    }

    const filteredData = galleryData.filter(
        (item) => item.category === value
    );

    console.log(value);
    setGalleryItems(filteredData);
};

And use it:

 {galleryData.map((item, index) => (
   <button
       key={index}
       onClick={() => filterGalley(item.category)}
       className={"filter-button " + (activeCategory === item.category ? 'active' : '')}
   >
       {item.category}
   </button>
))}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!