Detect Scroll Direction ReactJS
source link: https://dev.to/nadeemkhanrtm/detect-scroll-direction-reactjs-1gnp
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Posted on Nov 7
Detect Scroll Direction ReactJS
In these blog. I am detecting scroll direction either person id scrolling down or up. To use these concept you can make some better thing like Navbar. Render a Navbar when we scroll untill that it gets disappear. So I am explaining here only about scroll direction If you want the example then please let me know.
import React, {useEffect, useState, useCallback} from 'react';
import { Fragment } from 'react/cjs/react.production.min';
import styles from "./App.module.css";
const App = () => {
const [y,
setY] = useState(document.scrollingElement.scrollHeight);
const [scrollDirection,
setScrollDirection] = useState("you have not scrolled yet");
const handleNavigation = useCallback((e) => {
if (y > window.scrollY) {
setScrollDirection("Scrolling Up");
console.log("scrolling up");
} else if (y < window.scrollY) {
setScrollDirection("Scrolling Down");
console.log("scrolling down");
}
setY(window.scrollY)
}, [y]);
useEffect(() => {
window.addEventListener("scroll", handleNavigation);
return () => {
window.removeEventListener("scroll", handleNavigation);
};
}, [handleNavigation]);
return (
<Fragment>
<div className={styles.main_container}>
</div>
<div>{scrollDirection}</div>
</Fragment>
)
}
export default App
OutPut Result
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK