Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

55
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

7 months ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos