I have two <Route>
s created with react-router.
- /cards -> List of cards game
- /cards/1 -> Detail of card game #1
When the user clicks on the "Return to list", I want to scroll the user where he was on the list.
How can I do this?
I have two <Route>
s created with react-router.
When the user clicks on the "Return to list", I want to scroll the user where he was on the list.
How can I do this?
Working example at codesandbox
React Router v4 does not provide out of the box support for scroll restoration and as it currently stands they won't either. In section React Router V4 - Scroll Restoration of their docs you can read more about it.
So, it's up to every developer to write logic to support this although, we do have some tools to make this work.
.scrollIntoView()
can be called on an element and as you can guess, it scrolls it into view. Support is quite good, currently, 97% of browsers support it. Source: icanuse
<Link />
component can pass on stateReact Router's Link component has a to
prop which you can provide an object instead of a string. Here's who this looks.
<Link to={{ pathname: '/card', state: 9 }}>Card nine</Link>
We can use state to pass on information to the component that will be rendered. In this example, state is assigned a number, which will suffice in answering your question, you'll see later, but it can be anything. The route /card
rendering <Card />
will have access to the variable state now at props.location.state and we can use it as we wish.
When rendering the various cards, we add a unique class to each one. This way we have an identifier that we can pass on and know that this item needs to be scrolled into view when we navigate back to the card list overview.
<Cards />
renders a list, each item with a unique class;Link />
passes the unique identifier to <Card />
;<Card />
renders card details and a back button with the unique identifier;<Cards />
is mounted, .scrollIntoView()
scrolls to the item that was previously clicked using the data from props.location.state
.Below are some code snippets of various parts.
// Cards component displaying the list of available cards.
// Link's to prop is passed an object where state is set to the unique id.
class Cards extends React.Component {
componentDidMount() {
const item = document.querySelector(
".restore-" + this.props.location.state
);
if (item) {
item.scrollIntoView();
}
}
render() {
const cardKeys = Object.keys(cardData);
return (
<ul className="scroll-list">
{cardKeys.map(id => {
return (
<Link
to={{ pathname: `/cards/${id}`, state: id }}
className={`card-wrapper restore-${id}`}
>
{cardData[id].name}
</Link>
);
})}
</ul>
);
}
}
// Card compoment. Link compoment passes state back to cards compoment
const Card = props => {
const { id } = props.match.params;
return (
<div className="card-details">
<h2>{cardData[id].name}</h2>
<img alt={cardData[id].name} src={cardData[id].image} />
<p>
{cardData[id].description} <a href={cardData[id].url}>More...</a>
</p>
<Link
to={{
pathname: "/cards",
state: props.location.state
}}
>
<button>Return to list</button>
</Link>
</div>
);
};
// App router compoment.
function App() {
return (
<div className="App">
<Router>
<div>
<Route exact path="/cards" component={Cards} />
<Route path="/cards/:id" component={Card} />
</div>
</Router>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Since there is no answer for how to do this in a functional component, here's a hook solution I implemented for a project:
import React from 'react';
import { useHistory } from 'react-router-dom';
function useScrollMemory(): void {
const history = useHistory<{ scroll: number } | undefined>();
React.useEffect(() => {
const { push, replace } = history;
// Override the history PUSH method to automatically set scroll state.
history.push = (path: string) => {
push(path, { scroll: window.scrollY });
};
// Override the history REPLACE method to automatically set scroll state.
history.replace = (path: string) => {
replace(path, { scroll: window.scrollY });
};
// Listen for location changes and set the scroll position accordingly.
const unregister = history.listen((location, action) => {
window.scrollTo(0, action !== 'POP' ? 0 : location.state?.scroll ?? 0);
});
// Unregister listener when component unmounts.
return () => {
unregister();
};
}, [history]);
}
function App(): JSX.Element {
useScrollMemory();
return <div>My app</div>;
}
With this override solution, you need not to worry about passing the state in all of your Link
elements. An improvement would be making it generic so it's backwards compatible with the push
and replace
methods of history
but it wasn't a requirement in my particular case so I omitted it.
I'm using react-router-dom
but you could just as easily override the methods of the vanilla historyAPI.
One other possible solution to this is to render your /cards/:id
route as a full screen modal and keep the /cards
route mounted behind it
For full implementation using Redux you can see this on CodeSandbox.
I did this by utilizing the history API.
Save scroll position after a route change.
Restore the scroll position when the user clicks the back button.
Save the scroll position in getSnapshotBeforeUpdate
and restore it in componentDidUpdate
.
// Saving scroll position.
getSnapshotBeforeUpdate(prevProps) {
const {
history: { action },
location: { pathname }
} = prevProps;
if (action !== "POP") {
scrollData = { ...scrollData, [pathname]: window.pageYOffset };
}
return null;
}
// Restore scroll position.
componentDidUpdate() {
const {
history: { action },
location: { pathname }
} = this.props;
if (action === "POP") {
if (scrollData[pathname]) {
setTimeout(() =>
window.scrollTo({
left: 0,
top: scrollData[pathname],
behavior: "smooth"
})
);
} else {
setTimeout(window.scrollTo({ left: 0, top: 0 }));
}
} else {
setTimeout(window.scrollTo({ left: 0, top: 0 }));
}
}