Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

223
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!