Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

164
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda