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

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

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