D
D
DeniSidorenko2021-02-18 08:55:52
React
DeniSidorenko, 2021-02-18 08:55:52

How to do this kind of scroll check in React?

Good afternoon, there are sections under each other on the site
For example, as in the picture (there are more than 3 of them)
noname.png

The user scrolls, reaches the beginning of section 1 And when the section completely enters the screen (i.e. the top corner of the section is at the top of the screen) a class is added to example active (for the section itself) And so by analogy with 2 sections

I provide myself with an implementation in this way. We go through all the sections and write down their coordinates. And when the user scrolls, we add a check if, for example, scroll > an element from the array, add a class to the section with the given index. True, I do not provide the implementation itself in the code. thanks in advance

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
DeniSidorenko, 2021-02-18
@DeniSidorenko

It turned out to do something like this, only the question is, will it not be too loaded?

useEffect(() => {
    window.addEventListener('scroll', function (event){
      setScroll(window.scrollY > bannerPosition);
      if (window.scrollY < positions[0]) return;
      const index = positions.findIndex((el, i, arr) => window.scrollY < arr[i + 1]);

      const categoryAttribute = "[data-id=" + "'" + index + "'" + "]";
      const element = document.querySelector(categoryAttribute)

      const allElements = document.querySelectorAll('.menu-nav li span')
      for(let el of allElements){
        el.classList.remove('active')
      }

      if(element) element.classList.add('active')
      if(index === -1 && window.scrollY > positions[0]){
        allElements[allElements.length - 1].classList.add('active')
      }
    })

  },[bannerPosition, positions])

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question