Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

72
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda