• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

195
Vistas
How can we add active class to all items when they are clicked?

I was following the below answer but with this approach, the active class gets removed from the present clicked item once clicked on another item.

Can anyone suggest me some other solution in which we can toggle an active class on click?

class SideNavbar extends React.Component {
  state = {
    links: [
      {
        id: 1,
        name: "Link1",
        to: "/cms",
        className: "side_nav_item"
      },
      {
        id: 2,
        name: "Link2",
        to: "/cms",
        className: "side_nav_item"
      },
      {
        id: 3,
        name: "Link3",
        to: "/cms",
        className: "side_nav_item"
      },
      {
        id: 4,
        name: "Link4",
        to: "/cms",
        className: "side_nav_item"
      }
    ],
    activeLink: null
  };

  handleClick = id => {
    this.setState({ activeLink: id });
  };

  render() {
    const { links, activeLink } = this.state;

    return (
      <div>
        {links.map(link => {
          return (
            <div key={link.id}>
              <ul>
                <li
                  onClick={() => this.handleClick(link.id)}
                  className={
                    link.className +
                    (link.id === activeLink ? " active_item" : "")
                  }
                >
                  {link.name} {link.id === activeLink && "active!"}
                </li>
              </ul>
            </div>
          );
        })}
      </div>
    );
  }
}

https://stackoverflow.com/a/55518951/10744648

almost 3 years ago · Juan Pablo Isaza
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 Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda