0

I need to build a onScroll function that detects the largest html element on the screen. Based on IDS that are in an array.

If I was scrolling down the page and section1 took up more room than section2 I want to set that value into state.

import React, { useState } from 'react'

export default function Example() {
    let [biggestSection, setBiggestSection] = useState("")

    const handleOnScroll = (e) => {
        let sectionIDS = ['section1', 'section2', 'section3', 'section4', 'section5', 'section6']

   
        // When the user scrolls
        // I need to know what element is taking up the most room 
        // on the screen
        // then set it to the biggestSection using the setBiggestSection hook
    }

    return (
        <div onScroll={handleOnScroll}>
            <section id={"section1"}>
                {/* section content */}
            </section>
            <section id={"section2"}>
                {/* section content */}
            </section>
            <section id={"section3"}>
                {/* section content */}
            </section>
            <section id={"section4"}>
                {/* section content */}
            </section>
            <section id={"section5"}>
                {/* section content */}
            </section>
            <section id={"section6"}>
                {/* section content */}
            </section>
            <section id={"section7"}>
                {/* section content */}
            </section>
            <section id={"section8"}>
                {/* section content */}
            </section>
        </div>
    )
}



ELJAY91
  • 61
  • 1
  • 4

1 Answers1

0

Not sure why you want to calculate that on scroll but you can do something like this.

const handleOnScroll = (e) => {
  let sectionIDS = ['section1', 'section2', 'section3', 'section4', 'section5', 'section6']

  let largestSection;
  let maxHeight = 0;

  sectionIDS.forEach(sectionId => {
    const section = document.getElementById(sectionId);
    const sectionHeight = section.clientHeight;
    if (sectionHeight > maxHeight) {
      maxHeight = sectionHeight;
      largestSection = sectionId;
    }
  });

  setBiggestSection(largestSection);
}

I would consider using 'debounce' here.

Siddharth
  • 1,200
  • 8
  • 13