how can we identify onScoll event reaches a specific component? I have tried to use ref to scrollinto view thats works when we fire click event. But how it works user scroll down and reaches specific component, that time i should perform some task. how can we achive that?
import "./styles.css";
import { useRef, useEffect } from "react";
export default function App() {
const eipCard = useRef(null);
const salaryCard = useRef(null);
const salesCard = useRef(null);
const handleStickyHeader = () => {
//handle logic
// should trigger scroll reaches eip card
console.log("reaches eip card")
// should trigger scroll reaches salary card
console.log("reaches salary card")
// should trigger scroll reaches sales card
console.log("reaches sales card")
};
useEffect(() => {
if (typeof window !== "undefined") {
window.addEventListener("scroll", handleStickyHeader);
}
return () => window.removeEventListener("scroll", handleStickyHeader);
}, []);
return (
<div className="App">
<div
ref={eipCard}
style={{ height: "500px", backgroundColor: "red" }}
></div>
<div
ref={salaryCard}
style={{ height: "500px", backgroundColor: "blue" }}
></div>
<div
ref={salesCard}
style={{ height: "500px", backgroundColor: "blue" }}
></div>
</div>
);
}
You can use Intersection Observer API to create custom React hooks checking components in view. Here is the working Example