This content originally appeared on DEV Community and was authored by Nadeem Khan
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
This content originally appeared on DEV Community and was authored by Nadeem Khan
Nadeem Khan | Sciencx (2021-11-07T04:58:39+00:00) Detect Scroll Direction ReactJS. Retrieved from https://www.scien.cx/2021/11/07/detect-scroll-direction-reactjs/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.