dor.co
dor.co

Reputation: 43

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.

Upvotes: 3

Views: 1220

Answers (1)

Gass
Gass

Reputation: 9344

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)
    }
},[])

Upvotes: 1

Related Questions