How do you handle scroll restoration in a React-Router app

0 votes
With the help of proper code examples can you tell me How do you handle scroll restoration in a React-Router app?
Feb 23 in Node-js by Ashutosh
• 19,190 points
75 views

1 answer to this question.

0 votes

By default, React Router does not restore scroll positions when navigating. To handle scroll restoration, follow these steps:

1. Use useEffect with useLocation for Manual Scroll Restoration

Scrolls to the top on route changes.

import { useEffect } from "react";

import { useLocation } from "react-router-dom";

const ScrollToTop = () => {

  const { pathname } = useLocation();

  useEffect(() => {

    window.scrollTo(0, 0);

  }, [pathname]);

  return null;

};

export default ScrollToTop;

2. Use ScrollToTop in App.js

Wrap it inside the router to apply globally.

import { BrowserRouter as Router, Routes, Route } from "react-router-dom";

import ScrollToTop from "./ScrollToTop";

import Home from "./Home";

import About from "./About";

function App() {

  return (

    <Router>

      <ScrollToTop />

      <Routes>

        <Route path="/" element={<Home />} />

        <Route path="/about" element={<About />} />

      </Routes>

    </Router>

  );

}

export default App;



answered Feb 24 by Kavya

Related Questions In Node-js

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

How to Handle Jest Unit Testing for 'ɵcmp' in a React-in-Angular Hybrid App?

Encountering the 'ɵcmp' property error during Jest ...READ MORE

answered Dec 23, 2024 in Node-js by Navya
85 views
0 votes
1 answer

How do you implement routing in a React application?

Implementing Routing in a React Application (React ...READ MORE

answered Feb 23 in Node-js by Kavya
57 views
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

How do you implement breadcrumbs in a React-Router app?

Breadcrumbs help users navigate by showing the ...READ MORE

answered Feb 24 in Node-js by Kavya
62 views
0 votes
1 answer

How do you handle a large amount of data in React?

Handling Large Amounts of Data in React To ...READ MORE

answered Feb 24 in Node-js by Kavya
58 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP