I have multiple divs and I need, when scrolling down, it scrolls to the next div, and when scrolling up, it scrolls to the previous div.
There's a question related to this (Javascript: scroll from one div to the other when scrolling?) using JavaScript and jQuery, where it has an example in Fiddle, however, I'm not able to implement that example in React.
Fiddle example: http://jsfiddle.net/r3x7r/410/
This is what I have so far:
import { Image } from "react-bootstrap";
import { useEffect, useRef } from "react";
import "./styles.css";
export default function App() {
const div1 = useRef(null);
const div2 = useRef(null);
const executeScroll = () => {
if (div2.current) div2.current.scrollIntoView();
};
useEffect(() => {
const threshold = 0;
let lastScrollY = window.pageYOffset;
let ticking = false;
const updateScrollDir = () => {
const scrollY = window.pageYOffset;
if (Math.abs(scrollY - lastScrollY) < threshold) {
ticking = false;
return;
}
// check scrolling is down
if (scrollY > lastScrollY) {
if (div1.current && div2.current) {
if (scrollY >= 0 && scrollY <= div1.current.clientHeight) {
executeScroll();
}
}
}
lastScrollY = scrollY > 0 ? scrollY : 0;
ticking = false;
};
const onScroll = () => {
if (!ticking) {
window.requestAnimationFrame(updateScrollDir);
ticking = true;
}
};
window.addEventListener("scroll", onScroll);
return () => {
window.removeEventListener("scroll", onScroll);
};
});
return (
<>
<div ref={div1}>
<Image
className="div1-media d-block"
src="https://picsum.photos/800/600?random=2"
/>
</div>
<div ref={div2}>
<Image
className="div2-media d-block"
src="https://picsum.photos/800/600?random=4"
/>
</div>
</>
);
}
.App {
font-family: sans-serif;
text-align: center;
}
.div1-media,
.div2-media {
object-fit: cover;
width: 100%;
height: 100%;
}
Demo on CodeSandBox: https://codesandbox.io/s/scrolls-to-next-element-on-scrolling-element-forked-zswfw