Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested animated routes in React Router V6

I'm really struggling to implement something in React Router Version 6, that was relatively straight-forward in Version 5.

I'd like to not only animate between routes (which is now finally possible in Version 6 due to a recent commit to the library), but also to animate nested routes. Think sliding pages, within sliding pages.

Here is a CodeSandbox with what I have so far.

I'm using Framer Motion's AnimatePresence to detect exit animations. But React Router wants to re-animate the parent route, even if just the nested route has changed.

As you can see in the CodeSandbox demo, the routes are animating okay, but when clicking the "Next nested page" link, it also re-animates the whole page, which is not what's desired. What I'd like is for Page 1 to stay static while its' nested route animates. Obviously, when you click "Next page", the whole page should animate (moving from Page 1 to Page 2). But I can't seem to have my cake and eat it.

enter image description here

Has anyone been able to do this? Grumblings in the library and on the wider web are indicating that this may be impossible currently?

like image 791
shennan Avatar asked Oct 14 '25 14:10

shennan


1 Answers

The reason why AnimatePresence is re-animating the parent route upon child navigation is because of the key prop. When the key changes, React treats it as an entirely new component. Since the location.key will always change when a route changes, passing location.key to both Routes components will trigger the route animations every time.

The only solution I can think of is to manage the keys for both Routes components manually. If you change the URL structure to make the base route path /page1, the solution is pretty simple:

Forked Demo

To keep your current URL structure, you'll need to create a key for the top-level Routes comp that changes when navigating from / to /page2, but doesn't change when navigating from / to /nested1 or from /nested1 to /nested2.

like image 50
Stafford Rose Avatar answered Oct 17 '25 22:10

Stafford Rose