rey2197
rey2197

Reputation: 101

ReactJS frustrating element.scrollTop bug

I have this frustrating problem with scroll in my ReactJS and TailwindCSS project. I was trying to show element when viewport is on specific part of my website and to hide it when it's not.

function App() {
  const scrollRef = createRef()
  const [isVisible, setIsVisible] = useState(false);

  const handleScroll = () => {
    let heightToShow = 1000;
    const winScroll = document.querySelector('.App').scrollTop; 
    if (winScroll > heightToShow) {
      setIsVisible(true);
    } else {
      setIsVisible(false);
    }
  };

  return (
    <div onScroll={handleScroll} className="App scroll-smooth relative bg-secondary h-screen snap-y snap-mandatory overflow-x-hidden overflow-y-scroll flex flex-col">
      <div ref={scrollRef} />
      <Header />
      <About />
      <Skills />
      <Projects />
      <Contacts />
      <TopButton isVisible={isVisible} ref={scrollRef} />
    </div>
  );
}

export default App;

At first, i've tried using window.pageYOffset which didn't work, because the value always stayed at 0 and element didn't show up. With document.querySelector('.App').scrollTop I made the functionality work as needed, but I got this terrible bug, where if winScroll's value gets to heightToShow's value - my viewport jumps back to the original winScroll's value. So basically, It is almost impossible to scroll both ways with mousewheel past my heightToShow value.

Any thoughts on why it is happening?

Upvotes: 1

Views: 164

Answers (0)

Related Questions