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

222
Vistas
How to get the ID of div that I scroll to?

I want to get the ID of every div that I scroll to and keep the ID in my state.

I have a list of some div elements. I expect to store in my state the current ID of the div that I scroll to.

My code

import React, { useEffect, useState } from "react";

export default function App() {
  const [currentId, setCurrentId] = useState(null);

  useEffect(() => {
    // some code here
  }, []);

  return (
    <>
      <div style={{ height: 600, background: "#d7a1a1" }} id="div-1">
        <h1>div 1</h1>
      </div>
      <div style={{ height: 600, background: "#d7a1a1" }} id="div-2">
        <h1>div 2</h1>
      </div>
      <div style={{ height: 600, background: "#d7a1a1" }} id="div-3">
        <h1>div 3</h1>
      </div>
      <div style={{ height: 600, background: "#d7a1a1" }} id="div-4">
        <h1>div 4</h1>
      </div>
      <div style={{ height: 600, background: "#d7a1a1" }} id="div-5">
        <h1>div 5</h1>
      </div>
    </>
  );
}

So when I scroll to the first div I want to store in currentId state div-1, to the second the div-2 and so on.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can do something like so:

const [currentId, setCurrentId] = useState(null)
const [scrollPos, setScrollPos] = useState(0)

useEffect(() => {
    window.addEventListener('scroll', setScrollPos(window.pageYOffset))

    if(scrollPos <= 600) setCurrentId('div-1')
    else if(scrollPos > 600 && scrollPos <= 1200) setCurrentId('div-2')
    else if(scrollPos > 1200 && scrollPos <= 1800) setCurrentId('div-3')
    // and so ....

    return () => {
        window.removeEventListener('scroll', handleScroll)
    }
},[])
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