0

I am making mobile web using React.js.

How to toggle class to div when scroll down/up only in specific div ?

This is I tried so far. My code problem is that it toggle class only when reach to top.

const [scroll, setScroll] = useState(false);

 useEffect(() => {
   window.addEventListener("scroll", () => {
     setScroll(window.scrollY > 50);
   });
 }, []); 

<div class="area">This area can Scroll</div>
<div className={scroll ? "hide" : "show"}>toggle class here</div>
1
  • window.scrollY will give you the scroll value of the browser window, not the specific div. Use a reference to the element and scrollTop: stackoverflow.com/questions/4373667/… Commented May 12, 2021 at 7:00

2 Answers 2

1

Add an onScroll event to your div that you want to make scrollable and attach a reference to it using useRef hook. Everytime your div scrolls, fire a function handleScroll and set your scroll state accordingly. You will need to set some height and give overflow-y:scroll to your scrollable div to actually see it. This should help you out.

import React, { useState, useEffect } from "react";
import "./styles.css";

export default function App() {
  const [scroll, setScroll] = useState(false);
  const divRef = React.useRef();

  const handleScroll = (e) => {
    const scrolledFromTop = divRef.current.scrollTop;
    console.log(scrolledFromTop);
    setScroll(scrolledFromTop > 50);
  };

  return (
    <div className="App">
      <div className={scroll ? "hide" : "show"}>toggle class here</div>
      <div className="area" onScroll={handleScroll} ref={divRef}>
       
      </div>
    </div>
  );
}

You can run the codesandbox here. https://codesandbox.io/s/funny-sanderson-3otq4?file=/src/App.js:0-761

Sign up to request clarification or add additional context in comments.

Comments

0

Function handleScroll got included prop 'target' so useRef is not necessary.

import React, { useState, useEffect } from "react";
import "./styles.css";

export default function App() {
  const [scrolled, setScrolled] = useState(false);

  const handleScroll = (event) => {
    const scrolledFromTop = event.target.scrollTop;
    setScroll(scrolledFromTop > 50);
  };

  return (
    <div className="App">
      <div className={scrolled ? "hide" : "show"}>
        toggle class here
      </div>
      <div className="area" onScroll={handleScroll}></div>
    </div>
  );
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.