Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

73
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda