Advertisement
jakaria_hossain

React Page scroll and page link concurrently

Feb 9th, 2024
1,062
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // ... imports ...
  2.  
  3. const Page = ({ path, children }) => {
  4.     const ref = useRef();
  5.     const navigate = useNavigate();
  6.     const location = useLocation();
  7.  
  8.     const handleWheel = (e) => {
  9.         const target = e.deltaY > 0 ? 'next' : 'prev';
  10.         const sibling = ref.current[target + 'ElementSibling'];
  11.  
  12.         if (sibling) {
  13.             sibling.scrollIntoView({ behavior: 'smooth' });
  14.         }
  15.     };
  16.  
  17.     useEffect(() => {
  18.         const scrollHandler = () => {
  19.             const rect = ref.current.getBoundingClientRect();
  20.             const isInView = rect.top >= 0 && rect.bottom <= window.innerHeight;
  21.  
  22.             if (isInView && location.pathname !== path) {
  23.                 navigate(path);
  24.             }
  25.         };
  26.  
  27.         window.addEventListener('scroll', scrollHandler);
  28.         return () => {
  29.             window.removeEventListener('scroll', scrollHandler);
  30.         };
  31.     }, [path, navigate, location.pathname]);
  32.  
  33.     return (
  34.         <div ref={ref} onWheel={handleWheel}>
  35.             <h1>Page {path}</h1>
  36.             {children}
  37.         </div>
  38.     );
  39. };
  40.  
  41.  
  42. function App() {
  43.     return (
  44.         <div>
  45.             <Sidebar />
  46.             <Routes>
  47.                 {/* ... other routes ... */}
  48.                 <Route path="/cargo" element={<Page path="/cargo"><Cargo /></Page>} />
  49.                 <Route path="/pax" element={<Page path="/pax"><Pax /></Page>} />
  50.                 <Route path="/weather" element={<Page path="/weather"><WeatherPage /></Page>} />
  51.                 <Route path="/charter" element={<Page path="/charter"><Charter /></Page>} />
  52.                 <Route path="/vale" element={<Page path="/vale"><Vale /></Page>} />
  53.                 <Route path="/reporting" element={<Page path="/reporting"><Reporting /></Page>} />
  54.             </Routes>
  55.         </div>
  56.     );
  57. }
  58.  
  59. export default App;
  60.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement