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

162
Vistas
Toggle a class only to one element at each click of the mouse - React hooks

I'm trying to add and remove a class when clicking on an item of my header, but I struggle to do it and I don't know how to map the rendered items in the header component.

Here's the first part of the code with a function that works for routing and window.location.

I'm able to add the class but it gets added to each element clicked and it gets removed only when I click again on it.

import React, { useState } from 'react';

const Link = ({ href, children }) => {
  const [activeItem, setActiveItem] = useState(false);

  const onClick = (event) => {
    if (event.metaKey || event.ctrl) {
      return;
    }

    event.preventDefault();
    window.history.pushState({}, '', href);

    const navEvent = new PopStateEvent('popstate');
    window.dispatchEvent(navEvent);

    setActiveItem(!activeItem);
  };

  return (
    <a
      onClick={onClick}
      className={`item ${activeItem ? 'active' : ''}`}
      href={href}
    >
      {children}
    </a>
  );
};

export default Link;

Here's my header element instead:

import React from 'react';
import Link from './Link';
import Logo from './Logo';

const Header = () => {
  return (
    <div className="ui secondary pointing menu">
      <Link href="/">
        <Logo />
      </Link>

      <div className="pointing right menu">
        <Link href="/services">services</Link>
        <Link href="/works">works</Link>
        <Link href="/contacts">contacts</Link>
      </div>
    </div>
  );
};

export default Header;
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You need to make your link components aware of each other by lifting the state to your header component. Then you pass you tell your link components which link is currently selected by passing it as a prop and you also need to give them the ability to change which link is currently selected:

import React from 'react';
import Link from './Link';
import Logo from './Logo';

const Link = ({ href, children, isActive, handleClick }) => {
  
  const onClick = (event) => {
    if (event.metaKey || event.ctrl) {
      return;
    }
  
    event.preventDefault();
    window.history.pushState({}, '', href);
  
    const navEvent = new PopStateEvent('popstate');
    window.dispatchEvent(navEvent);
  
    handleClick();
  };
  
  return (
    <a
      onClick={onClick}
      className={`item ${isActive ? 'active' : ''}`}
      href={href}
    >
      {children}
    </a>
  );
};
  
export default Link;
const Header = () => {
  const [activeLink, setActiveLink] = useState(0)

  return (
    <div className="ui secondary pointing menu">
      <Link
        href="/"
        isActive={activeLink === 0}
        handleClick={() => setActiveLink(0)}
      >
        <Logo />
      </Link>

      <div className="pointing right menu">
        <Link
          href="/services"
          isActive={activeLink === 1}
          handleClick={() => setActiveLink(1)}
        >
          services
        </Link>
        <Link 
          href="/works"
          isActive={activeLink === 2}
          handleClick={() => setActiveLink(2)}
        >
          works
        </Link>
        <Link
          href="/contacts"
          isActive={activeLink === 3}
          handleClick={() => setActiveLink(3)}
        >
          contacts
        </Link>
      </div>
    </div>
  );
};

export default 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