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

123
Vistas
React way of selecting elements and adding event listeners

I'm building a portfolio site with gatsby where I have a sidebar on the left with some links (Home, about, work, etc.) and on the right there's the main content which is one long strip of sections. Clicking a link simply scrolls to that section. I would like for a link to be styled differently when the user reaches that section. I've found a solution in vanilla javascript to apply active state that works, but I don't know how to do this the react way.

useEffect(() => {
const navbarlinks = document.querySelectorAll("nav a");

const navbarlinksActive = () => {
  let position = window.scrollY + 200;
  navbarlinks.forEach((navbarlink) => {
    let section = document.querySelector(navbarlink.hash);
    if (position >= section.offsetTop && position <= section.offsetTop + section.offsetHeight) {
      navbarlink.classList.add("active");
    } else {
      navbarlink.classList.remove("active");
    }
  });
};

window.addEventListener("load", navbarlinksActive);
document.addEventListener("scroll", navbarlinksActive);

return () => {
  window.removeEventListener("load", navbarlinksActive);
  document.removeEventListener("scroll", navbarlinksActive);
};
}, []);

I'm selecting all the nav links, then looping through them, getting the hash property, which will match the id of the corresponding section which is then selected. Then the class is added or removed based on its position. This code is in the sidebar component where my links, which are gatsby Link elements, also are.

return (    
  <nav>
    <Link
      className="hover:text-clr-accent flex items-center py-2 px-4 transition"
      to="#home"
    >
      <i className="fa-solid fa-house w-6 text-center text-lg"></i>
      <span className="pl-2 text-lg">Home</span>
    </Link>

    <Link
      className="hover:text-clr-accent flex items-center py-2 px-4 transition"
      to="#resume"
    >
      <i className="fa-solid fa-file w-6 text-center text-lg"></i>
      <span className="pl-2 text-lg">Resume</span>
    </Link>

    <Link
      className="hover:text-clr-accent flex items-center py-2 px-4 transition"
      to="#about"
    >
      <i className="fa-solid fa-address-card w-6 text-center text-lg"></i>
      <span className="pl-2 text-lg">About me</span>
    </Link>

    <Link
      className="hover:text-clr-accent flex items-center py-2 px-4 transition"
      to="#work"
    >
      <i className="fa-solid fa-briefcase w-6 text-center text-lg"></i>
      <span className="pl-2 text-lg">My work</span>
    </Link>
  </nav>
);
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

  1. Instead of directly adding/removing the active class set the active link Id to state and render based on that. Otherwise react may overwrite your classes by rendering

  2. Don't use the load event listener instead just call navbarlinksActive(), the window is already loaded by the time your effect is called.

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