React Redirect Hook Infinte Loop - javascript

I don't know the reason but if I try use the Navigate Hook to redirect to a specific path when my desktop changes mode, it dives into a sort of "infinite loop " in the browser:
history.ts:633 Throttling navigation to prevent the browser from
hanging. See https://crbug.com/1038223. Command line switch
--disable-ipc-flooding-protection can be used to bypass the protection
react-dom.development.js:86 Warning: Maximum update depth exceeded.
This can happen when a component calls setState inside useEffect, but
useEffect either doesn't have a dependency array, or one of the
dependencies changes on every render.
My App.js
import "./App.scss";
import React, { Fragment, useEffect } from "react";
import { useMediaQuery } from "./hooks/MediaQuery";
import Desktop from "./Pages/Desktop/Desktop";
import { Route, Routes, Navigate } from "react-router-dom";
function App() {
return (
<Fragment>
<div className="App">
<Routes>
<Route
exact
path="*"
element={
useMediaQuery(750) ? (
<Desktop replace to="/" />
) : (
<Navigate replace to="/m" />
)
}
/>
</Routes>
</div>
</Fragment>
);
}
export default App;

It seems the issue is an unconditional redirect loop is created in mobile views, from "*" to "/m" which is matched by "*" and the Navigate component is rendered again.
To stop this you might consider moving the redirect into a component lifecycle and only redirect if not already on "/m". Here's a basic implementation using a useEffect hook in the media query hook.
import { useNavigate, useMatch } from "react-router-dom";
import { useEffect } from "react";
const useMediaQueryRedirect = (width) => {
const navigate = useNavigate();
const isMobileMatch = useMatch("/m");
useEffect(() => {
const checkWidth = () => {
if (window.innerWidth < width && !isMobileMatch) {
navigate("/m");
}
if (window.innerWidth >= width && isMobileMatch) {
navigate("/");
}
};
window.addEventListener("resize", checkWidth, { passive: true });
return () => {
window.removeEventListener("resize", checkWidth, { passive: true });
};
}, [isMobileMatch, navigate, width]);
};
Create a layout route to use the hook and render the appropriate nested routes.
import { Route, Routes, Outlet } from "react-router-dom";
const MediaLayout = () => {
useMediaQueryRedirect(750);
return <Outlet />;
};
...
return (
...
<Routes>
<Route element={<MediaLayout />}>
<Route path="/*" element={/* Main component routes */} />
<Route path="/m/*" element={/* Mobile component routes */} />
</Route>
</Routes>
...
);

Related

React Router V6 Re-renders on Route Change

When I navigate back and forth between routes, React Router re-renders memoized routes causing useEffect(() => []) to re-run and data to re-fetch. I'd like to prevent that and instead keep existing routes around but hidden in the dom. I'm struggling with "how" though.
The following is sample code for the problem:
import React, { useEffect } from "react";
import { BrowserRouter as Router, Route, Routes, useNavigate } from "react-router-dom";
export default function App() {
return (
<Router>
<Routes>
<Route path={"/"} element={<MemoizedRouteA />} />
<Route path={"/b"} element={<MemoizedRouteB />} />
</Routes>
</Router>
);
}
function RouteA() {
const navigate = useNavigate()
useEffect(() => {
alert("Render Router A");
}, []);
return (
<button onClick={() => { navigate('/b') }}>Go to B</button>
);
};
const MemoizedRouteA = React.memo(RouteA)
function RouteB() {
const navigate = useNavigate()
useEffect(() => {
alert("Render Router B");
}, []);
return (
<button onClick={() => { navigate('/') }}>Go to A</button>
);
}
const MemoizedRouteB = React.memo(RouteB)
Sandbox: https://codesandbox.io/s/wonderful-hertz-w9qoip?file=/src/App.js
With the above code, you'll see that the "alert" code is called whenever you tap a button or use the browser back button.
With there being so many changes of React Router over the years I'm struggling to find a solution for this.
When I navigate back and forth between routes, React Router re-renders
memoized routes causing useEffect(() => []) to re-run and data to
re-fetch. I'd like to prevent that and instead keep existing routes
around but hidden in the dom. I'm struggling with "how" though.
Long story short, you can't. React components rerender for one of three reasons:
Local component state is updated.
Passed prop values are updated.
The parent/ancestor component updates.
The reason using the memo HOC doesn't work here though is because the Routes component only matches and renders a single Route component's element prop at-a-time. Navigating from "/" to "/b" necessarily unmounts MemoizedRouteA and mounts MemoizedRouteB, and vice versa when navigating in reverse. This is exactly how RRD is intended to work. This is how the React component lifecycle is intended to work. Memoizing a component output can't do anything for when a component is being mounted/unmounted.
If what you are really trying to minimize/reduce/avoid is duplicate asynchronous calls and data fetching/refetching upon component mounting then what I'd suggest here is to apply the Lifting State Up pattern and move the state and useEffect call into a parent/ancestor.
Here's a trivial example using an Outlet component and its provided context, but the state could be provided by any other means such as a regular React context or Redux.
import React, { useEffect, useState } from "react";
import {
BrowserRouter as Router,
Route,
Routes,
Outlet,
useNavigate,
useOutletContext
} from "react-router-dom";
export default function App() {
const [users, setUsers] = useState(0);
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/users")
.then((response) => response.json())
.then(setUsers);
}, []);
return (
<Router>
<Routes>
<Route element={<Outlet context={{ users }} />}>
<Route path={"/"} element={<RouteA />} />
<Route path={"/b"} element={<RouteB />} />
</Route>
</Routes>
</Router>
);
}
function RouteA() {
const navigate = useNavigate();
return (
<div>
<button onClick={() => navigate("/b")}>Go to B</button>
</div>
);
}
function RouteB() {
const navigate = useNavigate();
const { users } = useOutletContext();
return (
<div>
<button onClick={() => navigate("/")}>Go to A</button>
<ul>
{users.map((user) => (
<li key={user.id}>
{user.name} : {user.email}
</li>
))}
</ul>
</div>
);
}

Why is state being lost in my app when passed via history.push()?

I've created the following very simple React app to simulate the behavior I'm seeing in my production app.
Root component:
import {
BrowserRouter as Router,
Route,
RouteComponentProps,
Switch,
} from "react-router-dom";
import { Home } from "./home";
import { SubRoute } from "./sub-route";
export default function Root(props) {
return (
<Router>
<Switch>
<Route path="/" exact>
<Home {...props} />
</Route>
<Route path="/sub-route" exact>
<SubRoute />
</Route>
</Switch>
</Router>
);
}
Home component:
import { LocationDescriptor } from "history";
import * as React from "react";
import { useHistory } from "react-router-dom";
import { TestLocationState } from "./sub-route";
export const Home = () => {
const history = useHistory();
return (
<>
<h1>Home</h1>
<button
onClick={() => {
const location: LocationDescriptor<TestLocationState> = {
pathname: "/sub-route",
state: {
name: "STATE PAYLOAD",
},
};
history.push(location);
}}
>
Pass state to sub route
</button>
</>
);
};
SubRoute component:
import * as React from "react";
import { useLocation } from "react-router-dom";
export type TestLocationState = {
name: string;
};
export const SubRoute = () => {
const { state } = useLocation<TestLocationState | undefined>();
return (
<>
<h1>Sub Route</h1>
<div>state: {JSON.stringify(state)}</div>
</>
);
};
In the dummy app, when I click the button in the Home component which calls history.push(), passing a location object with a state property, the state is not only successfully passed to the SubRoute component, but if I refresh or hard refresh, the state value is still available.
In my production app (a completely separate app that includes the above in addition to, of course a lot of other stuff), state is successfully passed to the SubRoute component, but it is not retained upon refresh. It is undefined.
I'm very confused as to what could be causing different behavior in my production app versus my test app. Is it a React Router thing? Thoughts?
It turns out that another developer on the team had added this line of code in part of the application that was wiping out the state:
https://github.com/preactjs/preact-router#redirects

useHistory not defined in react custom Hook

I want to have a AI Voice assistant Alan AI to be integrated in my react app
So basically want to redirect pages using voice command.
But the problem is that, I want to use useHistory hook's push method to change pages, but whenever I access the variable it is undefined, I do not want to use window.location.href as it refreshes the app every time,
Can anyone suggest me where I am wrong usnig this hook/ or any other alternatives
import { useCallback, useEffect, useState } from "react";
import { useHistory } from "react-router-dom";
import { useCartContext } from "../context/cart_context";
import { useThemeContext } from "../context/theme_context";
import alanBtn from "#alan-ai/alan-sdk-web";
const COMMANDS = {
OPEN_CART: "open-cart",
TOGGLE_THEME: "toggle-theme",
};
const useAlan = () => {
let history = useHistory();
const { theme, toggleTheme } = useThemeContext();
const { cart } = useCartContext();
const [alanInstance, setAlanInstance] = useState(null);
const openCart = useCallback(() => {
if (cart.length < 1) {
alanInstance.playText("cart is empty");
return;
}
alanInstance.playText("opening cart");
history.push("/cart");
// window.location.href = "/cart";
}, [alanInstance]);
const changeTheme = useCallback(() => {
alanInstance.playText("changing theme");
toggleTheme();
});
useEffect(() => {
window.addEventListener(COMMANDS.OPEN_CART, openCart);
window.addEventListener(COMMANDS.TOGGLE_THEME, changeTheme);
return () => {
window.removeEventListener(COMMANDS.OPEN_CART, openCart);
window.removeEventListener(COMMANDS.TOGGLE_THEME, changeTheme);
};
}, [openCart, changeTheme]);
useEffect(() => {
// history.push("/cart");
// this also gives same error
if (alanInstance != null) return;
setAlanInstance(
alanBtn({
key: process.env.REACT_APP_ALAN_KEY,
onCommand: ({ command }) => {
window.dispatchEvent(new CustomEvent(command));
},
})
);
}, []);
return null;
};
export default useAlan;
Every thing work's fine, voice is detected and the openCart function is ran,
it's just that history is undefined
Error:
TypeError: Cannot read property 'push' of undefined
(anonymous function)
C:/Users/Sachin Verma/Desktop/Web Dev/React-E-Commerce-v2/src/hooks/useAlan.js:28
25 | }
26 | alanInstance.playText("opening cart");
27 |
> 28 | history.push("/cart");
| ^ 29 | // window.location.href = "/cart";
30 | }, [alanInstance]);
31 |
App.js code:
import React, { useState, useEffect } from "react";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import { useThemeContext } from "./context/theme_context";
import useAlan from "./hooks/useAlan";
import { Navbar, Sidebar, Footer } from "./components";
import {
Home,
SingleProduct,
Cart,
Checkout,
Error,
About,
Products,
PrivateRoute,
AuthWrapper,
Scan,
History,
ItemList,
} from "./pages";
function App() {
const { theme } = useThemeContext();
useAlan();
useEffect(() => {
if (theme === "dark-theme") {
// set dark mode theme
document.documentElement.className = "dark-theme";
} else {
// remove dark mode
document.documentElement.className = "light-theme";
}
}, [theme]);
return (
<AuthWrapper>
<Router>
<Navbar />
<Sidebar />
<Switch>
<Route exact path="/">
<Home />
</Route>
<Route exact path="/about">
<About />
</Route>
<Route exact path="/cart">
<Cart />
</Route>
<Route exact path="/products">
<Products />
</Route>
<PrivateRoute exact path="/history">
<History />
</PrivateRoute>
<PrivateRoute exact path="/scan">
<Scan />
<ItemList />
</PrivateRoute>
<Route exact path="/products/:id" children={<SingleProduct />} />
<PrivateRoute exact path="/checkout">
<Checkout />
</PrivateRoute>
<Route path="*">
<Error />
</Route>
</Switch>
<Footer />
</Router>
</AuthWrapper>
);
}
export default App;
This happens when you are not properly nesting your application inside a valid Router which provides context for the history object. Make sure your top-level code is put inside a proper Router object context:
import { BrowserRouter } from "react-router-dom";
function App() {
return (
<BrowserRouter>
...(components that use react-router-hooks)
</BrowserRouter>
);
}
Same goes for React-Native: NativeRouter.
useHistory has changed in v6, useHistory is now useNavigate and we can use it as follows:
instead of:
const history = useHistory()
history.push('/')
we now use:
const navigate = useNavigate()
naviaget('/')
If you work in App.js, you will need to move your
<Router> </Router>
of there to your index.js
and wrap it like that:
<Router>
<App />
</Router>
and it should work like a charm.

React D3 component did not get unmounted upon (component) redirect using history.push()

React D3 component did not get unmounted upon (component) redirect using the following approach. That is, in a SPA, while on 'graphA', clicking a button redirects to 'graphB'. 'graphB' is rendered, however, 'graphA' is still visible. Thoughts on how I can remove/unmount 'graphA' such that only 'graphB' is visible. I tried calling ReactDOM.unmountComponentAtNode() in various React lifecycle hooks with no success.
this.props.history.push({ pathname: '/graphB' })
Assuming you're using React Router, this is how to use a Switch component. It will render the component for the first path that matches.
import React, { Component } from 'react';
import { render } from 'react-dom';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
const A = () => <h1>A</h1>
const B = () => <h1>B</h1>
const Landing = ({ history }) => {
const goToA = () => {
history.push('a');
}
const goToB = () => {
history.push('b');
}
return (
<div>
<button onClick={goToA}>Go to A</button>
<button onClick={goToB}>Go to B</button>
</div>
)
}
const App = ({ history }) => {
return (
<Switch>
<Route exact path="/" component={Landing} />
<Route path="/a" component={A} />
<Route path="/a" component={A} />
</Switch>
)
}
render(
<BrowserRouter>
<App />
</BrowserRouter>
, document.getElementById('root'));
Live example here.

react-router scroll to top on every transition

I have an issue when navigating into another page, its position will remain like the page before. So it won't scroll to top automatically.
I've also tried to use window.scrollTo(0, 0) on onChange router. I've also used scrollBehavior to fix this issue but it didn't work. Any suggestions about this?
but classes are so 2018
ScrollToTop implementation with React Hooks
ScrollToTop.js
import { useEffect } from 'react';
import { withRouter } from 'react-router-dom';
function ScrollToTop({ history }) {
useEffect(() => {
const unlisten = history.listen(() => {
window.scrollTo(0, 0);
});
return () => {
unlisten();
}
}, []);
return (null);
}
export default withRouter(ScrollToTop);
Usage:
<Router>
<Fragment>
<ScrollToTop />
<Switch>
<Route path="/" exact component={Home} />
</Switch>
</Fragment>
</Router>
ScrollToTop can also be implemented as a wrapper component:
ScrollToTop.js
import React, { useEffect, Fragment } from 'react';
import { withRouter } from 'react-router-dom';
function ScrollToTop({ history, children }) {
useEffect(() => {
const unlisten = history.listen(() => {
window.scrollTo(0, 0);
});
return () => {
unlisten();
}
}, []);
return <Fragment>{children}</Fragment>;
}
export default withRouter(ScrollToTop);
Usage:
<Router>
<ScrollToTop>
<Switch>
<Route path="/" exact component={Home} />
</Switch>
</ScrollToTop>
</Router>
React 16.8+
If you are running React 16.8+ this is straightforward to handle with a component that will scroll the window up on every navigation:
Here is in scrollToTop.js component
import { useEffect } from "react";
import { useLocation } from "react-router-dom";
export default function ScrollToTop() {
const { pathname } = useLocation();
useEffect(() => {
window.scrollTo(0, 0);
}, [pathname]);
return null;
}
Then render it at the top of your app, but below Router
Here is in app.js
import ScrollToTop from "./scrollToTop";
function App() {
return (
<Router>
<ScrollToTop />
<App />
</Router>
);
}
Or in index.js
import ScrollToTop from "./scrollToTop";
ReactDOM.render(
<BrowserRouter>
<ScrollToTop />
<App />
</BrowserRouter>
document.getElementById("root")
);
This answer is only for v4 and not later versions.
The documentation for React Router v4 contains code samples for scroll restoration. Here is their first code sample, which serves as a site-wide solution for “scroll to the top” when a page is navigated to:
class ScrollToTop extends Component {
componentDidUpdate(prevProps) {
if (this.props.location !== prevProps.location) {
window.scrollTo(0, 0)
}
}
render() {
return this.props.children
}
}
export default withRouter(ScrollToTop)
Then render it at the top of your app, but below Router:
const App = () => (
<Router>
<ScrollToTop>
<App/>
</ScrollToTop>
</Router>
)
// or just render it bare anywhere you want, but just one :)
<ScrollToTop/>
^ copied directly from the documentation
Obviously this works for most cases, but there is more on how to deal with tabbed interfaces and why a generic solution hasn't been implemented.
This answer is for legacy code, for router v4+ check other answers
<Router onUpdate={() => window.scrollTo(0, 0)} history={createBrowserHistory()}>
...
</Router>
If it's not working, you should find the reason. Also inside componentDidMount
document.body.scrollTop = 0;
// or
window.scrollTo(0,0);
you could use:
componentDidUpdate() {
window.scrollTo(0,0);
}
you could add some flag like "scrolled = false" and then in update:
componentDidUpdate() {
if(this.scrolled === false){
window.scrollTo(0,0);
scrolled = true;
}
}
A React Hook you can add to your Route component. Using useLayoutEffect instead of custom listeners.
import React, { useLayoutEffect } from 'react';
import { Switch, Route, useLocation } from 'react-router-dom';
export default function Routes() {
const location = useLocation();
// Scroll to top if path changes
useLayoutEffect(() => {
window.scrollTo(0, 0);
}, [location.pathname]);
return (
<Switch>
<Route exact path="/">
</Route>
</Switch>
);
}
Update: Updated to use useLayoutEffect instead of useEffect, for less visual jank. Roughly this translates to:
useEffect: render components -> paint to screen -> scroll to top (run effect)
useLayoutEffect: render components -> scroll to top (run effect) -> paint to screen
Depending on if you're loading data (think spinners) or if you have page transition animations, useEffect may work better for you.
For react-router v4, here is a create-react-app that achieves the scroll restoration: http://router-scroll-top.surge.sh/.
To achieve this you can create decorate the Route component and leverage lifecycle methods:
import React, { Component } from 'react';
import { Route, withRouter } from 'react-router-dom';
class ScrollToTopRoute extends Component {
componentDidUpdate(prevProps) {
if (this.props.path === this.props.location.pathname && this.props.location.pathname !== prevProps.location.pathname) {
window.scrollTo(0, 0)
}
}
render() {
const { component: Component, ...rest } = this.props;
return <Route {...rest} render={props => (<Component {...props} />)} />;
}
}
export default withRouter(ScrollToTopRoute);
On the componentDidUpdate we can check when the location pathname changes and match it to the path prop and, if those satisfied, restore the window scroll.
What is cool about this approach, is that we can have routes that restore scroll and routes that don't restore scroll.
Here is an App.js example of how you can use the above:
import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
import Lorem from 'react-lorem-component';
import ScrollToTopRoute from './ScrollToTopRoute';
import './App.css';
const Home = () => (
<div className="App-page">
<h2>Home</h2>
<Lorem count={12} seed={12} />
</div>
);
const About = () => (
<div className="App-page">
<h2>About</h2>
<Lorem count={30} seed={4} />
</div>
);
const AnotherPage = () => (
<div className="App-page">
<h2>This is just Another Page</h2>
<Lorem count={12} seed={45} />
</div>
);
class App extends Component {
render() {
return (
<Router>
<div className="App">
<div className="App-header">
<ul className="App-nav">
<li><Link to="/">Home</Link></li>
<li><Link to="/about">About</Link></li>
<li><Link to="/another-page">Another Page</Link></li>
</ul>
</div>
<Route exact path="/" component={Home} />
<ScrollToTopRoute path="/about" component={About} />
<ScrollToTopRoute path="/another-page" component={AnotherPage} />
</div>
</Router>
);
}
}
export default App;
From the code above, what is interesting to point out is that only when navigating to /about or /another-page the scroll to top action will be preformed. However when going on / no scroll restore will happen.
The whole codebase can be found here: https://github.com/rizedr/react-router-scroll-top
It is noteable that the onUpdate={() => window.scrollTo(0, 0)} method is outdated.
Here is a simple solution for react-router 4+.
const history = createBrowserHistory()
history.listen(_ => {
window.scrollTo(0, 0)
})
<Router history={history}>
React hooks 2020 :)
import React, { useLayoutEffect } from 'react';
import { useLocation } from 'react-router-dom';
const ScrollToTop: React.FC = () => {
const { pathname } = useLocation();
useLayoutEffect(() => {
window.scrollTo(0, 0);
}, [pathname]);
return null;
};
export default ScrollToTop;
FOR 'REACT-ROUTER-DOM v6 & above'
I solved the following issue by creating a wrapper function and wrapping it around all the routes.
Follow the following steps:
1: You need to import the following:
import {Routes, Route, BrowserRouter as Router, useLocation} from 'react-router-dom';
import {useLayoutEffect} from 'react';
2: Write a wrapper function just above the "App" function:
const Wrapper = ({children}) => {
const location = useLocation();
useLayoutEffect(() => {
document.documentElement.scrollTo(0, 0);
}, [location.pathname]);
return children
}
3: Now wrap your routes within the wrapper function:
<BrowserRouter>
<Wrapper>
<Navbar />
<Routes>
<Route exact path="/" element={<Home/>} />
<Route path="/Products" element={<Products/>} />
<Route path="/Login" element={<Login/>} />
<Route path="/Aggressive" element={<Aggressive/>} />
<Route path="/Attendance" element={<Attendance/>} />
<Route path="/Choking" element={<Choking/>} />
<Route path="/EmptyCounter" element={<EmptyCounter/>} />
<Route path="/FaceMask" element={<FaceMask/>} />
<Route path="/Fainting" element={<Fainting/>} />
<Route path="/Smoking" element={<Smoking/>} />
<Route path="/SocialDistancing" element={<SocialDistancing/>} />
<Route path="/Weapon" element={<Weapon/>} />
</Routes>
<Footer />
</Wrapper>
</BrowserRouter>
This should solve the issue.
I had the same issue with my application.Using the below code snippet helped me scroll to the top of the page on click of the next button.
<Router onUpdate={() => window.scrollTo(0, 0)} history= {browserHistory}>
...
</Router>
However, the issue still persisted on browser back. After a lot of trials, realized that this was because of the browser window's history object, which has a property scrollRestoration which was set to auto.Setting this to manual solved my problem.
function scrollToTop() {
window.scrollTo(0, 0)
if ('scrollRestoration' in history) {
history.scrollRestoration = 'manual';
}
}
<Router onUpdate= {scrollToTop} history={browserHistory}>
....
</Router>
In your main component.
Just add this React Hooks (in case you are not using a React class) :
const oldPage = useRef(pathname)
useEffect(() => {
if (pathname !== oldPage.current) {
try {
window.scroll({
top: 0,
left: 0,
behavior: 'smooth'
})
} catch (error) {
// for older browser
window.scrollTo(0, 0)
}
oldPage.current = pathname
}
}, [pathname])
I want to share my solution for those who are using react-router-dom v5 since none of these v4 solutions did the work for me.
What solved my problem was installing react-router-scroll-top and put the wrapper in the <App /> like this:
const App = () => (
<Router>
<ScrollToTop>
<App/>
</ScrollToTop>
</Router>
)
and that's it! it worked!
Hooks are composable, and since React Router v5.1 we have a useHistory() hook. So based off #zurfyx's answer I've created a re-usable hook for this functionality:
// useScrollTop.ts
import { useHistory } from 'react-router-dom';
import { useEffect } from 'react';
/*
* Registers a history listener on mount which
* scrolls to the top of the page on route change
*/
export const useScrollTop = () => {
const history = useHistory();
useEffect(() => {
const unlisten = history.listen(() => {
window.scrollTo(0, 0);
});
return unlisten;
}, [history]);
};
This was my approach based on what everyone else had done in previous posts. Wondering if this would be a good approach in 2020 using location as a dependency to prevent re-renders?
import React, { useEffect } from 'react';
import { useLocation } from 'react-router-dom';
function ScrollToTop( { children } ) {
let location = useLocation();
useEffect( () => {
window.scrollTo(0, 0);
}, [ location ] );
return children
}
August-2021
Rather then doing it in every page you can do this in App.js
import { useLocation } from "react-router-dom";
const location = useLocation();
useEffect(() => {
window.scrollTo(0,0);
}, [location]);
Setting location in useEffect will make sure to scroll to top on every path change.
2021 (React 16) - Based off the comments from #Atombit
Below scrolls to top, but also preserves historic scroll positions.
function ScrollToTop() {
const history = useHistory()
useEffect(() => {
const unlisten = history.listen((location, action) => {
if (action !== 'POP') {
window.scrollTo(0, 0)
}
})
return () => unlisten()
}, [])
return (null)
}
Usage:
<Router>
<ScrollToTop />
<Switch>
<Route path="/" exact component={Home} />
</Switch>
</Router>
My solution: a component that I'm using in my screens components (where I want a scroll to top).
import { useLayoutEffect } from 'react';
const ScrollToTop = () => {
useLayoutEffect(() => {
window.scrollTo(0, 0);
}, []);
return null;
};
export default ScrollToTop;
This preserves scroll position when going back.
Using useEffect() was buggy for me, when going back the document would scroll to top and also had a blink effect when route was changed in an already scrolled document.
Utilizing hooks, you can simply insert window.scrollTo(0,0) in your useEffect in your code base. Simply implement the code snippet in your app and it should load each page at the top of it's window.
import { useEffect } from 'react';
useEffect(() => {
window.scrollTo(0, 0);
}, []);
With smooth scroll option
import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';
export default function ScrollToTop() {
const { pathname } = useLocation();
useEffect(() => {
window.scrollTo({
top: 0,
left: 0,
behavior: 'smooth',
});
}, [pathname]);
return null;
}
...
<Router>
<ScrollToTop />
...
</Router>
Since, I use function components, here is how I managed to achieve it.
import { useEffect } from 'react';
import { BrowserRouter, Routes, Route, useLocation } from 'react-router-dom';
function ScrollToTop() {
const { pathname } = useLocation();
useEffect(() => {
window.scrollTo(0, 0);
}, [pathname]);
return null;
}
const IndexRoutes = () => {
return (
<BrowserRouter>
<ScrollToTop />
<Routes>
<Route exact path="/">
<Home />
</Route>
/* list other routes below */
</Routes>
</BrowserRouter>
);
};
export default IndexRoutes;
You can also refer the code from the below link
https://reactrouter.com/web/guides/scroll-restoration
For me, window.scrollTo(0, 0) and document.documentElement.scrollTo(0, 0) didn't work on all my screens (only worked on 1 screen).
Then, I realized that the overflow (where scrolling is allowed) of my screens were not in window (because we have some static points, so we putted the overflow: auto in other div).
I did the following test to realize this:
useEffect(() => {
const unlisten = history.listen(() => {
console.log(document.documentElement.scrollTop)
console.log(window.scrollTop)
window.scrollTo(0, 0);
});
return () => {
unlisten();
}
}, []);
In all the logs, I got 0.
So, I looked for which container I had the scroll in and put an id:
<div id="SOME-ID">
...
</div>
And in my ScrollToTop component I put:
useEffect(() => {
const unlisten = history.listen(() => {
window.scrollTo(0, 0);
document.getElementById("SOME-ID")?.scrollTo(0, 0)
});
return () => {
unlisten();
}
}, []);
Now, when I go to a new route with history.push("/SOME-ROUTE") my screen go to the top
2022 November Update
Nothing work in react latest version 18.2.0 and react-router-dom 6.4.3. So I implemented this. Worked for me.Hope this helpful for anyone.
ScrollToTop.js
import { useEffect } from "react";
import { useLocation } from "react-router-dom";
export default function ScrollToTop() {
const { pathname } = useLocation();
useEffect(() => {
const body = document.querySelector('#root');
body.scrollIntoView({
behavior: 'smooth'
}, 500)
}, [pathname]);
return null;
}
Then import and add to browser router in index.js or App.js where your routes defined.
import { BrowserRouter, Routes, Route } from "react-router-dom";
import ScrollToTop from "./ScrollToTop";
function App() {
return (
<div>
<BrowserRouter>
<ScrollToTop />
<Routes>
//your routes
</Routes>
</BrowserRouter>
</div>
);
}
export default App;
(Note: Make sure the index.html div id="root".)
I wrote a Higher-Order Component called withScrollToTop. This HOC takes in two flags:
onComponentWillMount - Whether to scroll to top upon navigation (componentWillMount)
onComponentDidUpdate - Whether to scroll to top upon update (componentDidUpdate). This flag is necessary in cases where the component is not unmounted but a navigation event occurs, for example, from /users/1 to /users/2.
// #flow
import type { Location } from 'react-router-dom';
import type { ComponentType } from 'react';
import React, { Component } from 'react';
import { withRouter } from 'react-router-dom';
type Props = {
location: Location,
};
type Options = {
onComponentWillMount?: boolean,
onComponentDidUpdate?: boolean,
};
const defaultOptions: Options = {
onComponentWillMount: true,
onComponentDidUpdate: true,
};
function scrollToTop() {
window.scrollTo(0, 0);
}
const withScrollToTop = (WrappedComponent: ComponentType, options: Options = defaultOptions) => {
return class withScrollToTopComponent extends Component<Props> {
props: Props;
componentWillMount() {
if (options.onComponentWillMount) {
scrollToTop();
}
}
componentDidUpdate(prevProps: Props) {
if (options.onComponentDidUpdate &&
this.props.location.pathname !== prevProps.location.pathname) {
scrollToTop();
}
}
render() {
return <WrappedComponent {...this.props} />;
}
};
};
export default (WrappedComponent: ComponentType, options?: Options) => {
return withRouter(withScrollToTop(WrappedComponent, options));
};
To use it:
import withScrollToTop from './withScrollToTop';
function MyComponent() { ... }
export default withScrollToTop(MyComponent);
Here is another method.
For react-router v4 you can also bind a listener to change in history event, in the following manner:
let firstMount = true;
const App = (props) => {
if (typeof window != 'undefined') { //incase you have server-side rendering too
firstMount && props.history.listen((location, action) => {
setImmediate(() => window.scrollTo(0, 0)); // ive explained why i used setImmediate below
});
firstMount = false;
}
return (
<div>
<MyHeader/>
<Switch>
<Route path='/' exact={true} component={IndexPage} />
<Route path='/other' component={OtherPage} />
// ...
</Switch>
<MyFooter/>
</div>
);
}
//mounting app:
render((<BrowserRouter><Route component={App} /></BrowserRouter>), document.getElementById('root'));
The scroll level will be set to 0 without setImmediate() too if the route is changed by clicking on a link but if user presses back button on browser then it will not work as browser reset the scroll level manually to the previous level when the back button is pressed, so by using setImmediate() we cause our function to be executed after browser is finished resetting the scroll level thus giving us the desired effect.
with React router dom v4 you can use
create a scrollToTopComponent component like the one below
class ScrollToTop extends Component {
componentDidUpdate(prevProps) {
if (this.props.location !== prevProps.location) {
window.scrollTo(0, 0)
}
}
render() {
return this.props.children
}
}
export default withRouter(ScrollToTop)
or if you are using tabs use the something like the one below
class ScrollToTopOnMount extends Component {
componentDidMount() {
window.scrollTo(0, 0)
}
render() {
return null
}
}
class LongContent extends Component {
render() {
<div>
<ScrollToTopOnMount/>
<h1>Here is my long content page</h1>
</div>
}
}
// somewhere else
<Route path="/long-content" component={LongContent}/>
hope this helps for more on scroll restoration vist there docs hare react router dom scroll restoration
In your router.js, just add this function in the router object. This will do the job.
scrollBehavior() {
document.getElementById('app').scrollIntoView();
},
Like this,
**Routes.js**
import vue from 'blah!'
import Router from 'blah!'
let router = new Router({
mode: 'history',
base: process.env.BASE_URL,
scrollBehavior() {
document.getElementById('app').scrollIntoView();
},
routes: [
{ url: "Solar System" },
{ url: "Milky Way" },
{ url: "Galaxy" },
]
});
Using useEffect() - Solution for Functional Component
useEffect(() => {
window.history.scrollRestoration = 'manual';}, []);
My only solution was to add a line of code to each file like for example:
import React from 'react';
const file = () => { document.body.scrollTop = 0; return( <div></div> ) }
I used Typescript in my project. This worked for me:
// ScrollToTop.tsx
import {useEffect, useRef} from 'react'
import {withRouter} from 'react-router-dom'
const ScrollToTopComponent = () => {
const mounted = useRef(false)
useEffect(() => {
if (!mounted.current) {
//componentDidMount
mounted.current = true
} else {
//componentDidUpdate
window.scrollTo(0, 0)
}
})
return null
}
export const ScrollToTop = withRouter(ScrollToTopComponent)
// usage in App.tsx
export default function App() {
return (
<Router>
<ScrollToTop />
<OtherRoutes />
</Router>
)
}
For my app, it's essential to have ability to scroll up when navigating by links. But it's also essential to not scroll anything when clicking on tab labels (which are also links). Also, my app has an advanced layout so scrollable containers could be different depending on the layout of the current page and where the link follows.
So here's my solution that works for me:
Introduce RouterLink wrapper around react-router-dom's Link that adds onClick handler. When link is clicked, it finds the nearest scrolled container and scrolls it up. It's possible to opt-out of this behavior by specifying preserveScroll (that's the default behavior of the original Link.
Hope that helps.
// Helper to find nearest scrolled parent of a given node
const getScrollParent = (node) => {
if (!node) {
return null;
}
if (node.scrollTop > 0) {
return node;
} else {
return getScrollParent(node.parentNode);
}
};
interface RouterLinkProps extends LinkProps {
preserveScroll?: boolean;
}
export const RouterLink: React.FC<RouterLinkProps> = ({ preserveScroll = false, ...linkProps }) => {
const handleClick = useCallback(
(val) => {
const targetEl = val?.target;
if (!targetEl || preserveScroll) {
return;
}
const scrolledContainer = getScrollParent(targetEl);
if (scrolledContainer) {
scrolledContainer.scrollTo({
top: 0,
left: 0,
behavior: 'smooth',
});
}
},
[preserveScroll],
);
const extraProps = useMemo(() => {
if (!preserveScroll) {
return {
onClick: handleClick,
};
}
return {};
}, [handleClick, preserveScroll]);
return <Link {...linkProps} {...extraProps} />;
};
Now, I can use this wrapper and get desired behavior and enough control to adjust it. Like this:
<RouterLink to="/some/path">My Link that scrolls up</RouterLink>

Categories