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

149
Vistas
How to optimize toggling className between different menu items by React?

I have header component, where I want to toggle className between all the elements of menu (if one of the elements of menu is active and user is clicking to another element - this element become active and all others no). I have a code like this

import React, { useState } from 'react';
import './header.scss';

export const Header = ({ favoriteCount }) => {
  const [activeIndex, setActiveIndex] = useState(0);
  function toggleClass(index) {
    setActiveIndex(index);
  }

  return (
    <header className="header">
      <div className="container header-container">
        <ul className="header-menu">
          <li>
            <a
              className={
                activeIndex === 0
                  ? 'header-menu__link active'
                  : 'header-menu__link'
              }
              onClick={() => {
                toggleClass(0);
              }}
              href="##"
            >
              Characters
            </a>
          </li>
          <li>
            <a
              className={
                activeIndex === 1
                  ? 'header-menu__link active'
                  : 'header-menu__link'
              }
              onClick={() => {
                toggleClass(0);
              }}
              href="##"
            >
              Favorites
            </a>
          </li>
        </ul>
        <div className="header-favorite-count">
          <i className="far fa-heart"></i>
          {favoriteCount}
        </div>
      </div>
    </header>
  );
};

and styles to visualise toggling classes

  &-menu__link {
    color: lightgray;
  }

  .active {
    color: #fff;
  }

This approach is working but looks creepy. Maybe somebody knows how to optimize it?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I wouldn't use the index, I'd use the text of the item. I'd also include that text in the href so that there's an indication of what the anchor leads to. To avoid repeated code, you might put the menu items in a reusable array, something like this:

const menuItems = [
    "Characters",
    "Favorites",
];

export const Header = ({ favoriteCount }) => {
    const [activeItem, setActiveItem] = useState("");

    const setActiveItem = useCallback((event) => {
        setActiveItem(event.currentTarget.href.substring(2));
    }, []);

    const list = menuItems.map(item =>
        <li key={item}>
            <a
                className={`header-menu__link ${item === activeItem ? "active" : ""}`}
                onClick={setActiveItem}
                href={"##" + item}>
                {item}
            </a>
        </li>
    );
  
    return (
        <header className="header">
            <div className="container header-container">
                <ul className="header-menu">
                    {list}}
                </ul>
                <div className="header-favorite-count">
                    <i className="far fa-heart"></i>
                    {favoriteCount}
                </div>
            </div>
        </header>
    );
};
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