6

I've created some animations that I'd like to use for navigating between routes in my application. I have a back button visible on certain pages that allows the users to pop off the navigation stack to access the most recent page. I'd like two different animations, one for navigating deeper in the stack and one for popping back to the most recent page. I'd like to use history.goBack(), but there seems to be no way to pass a state and thus use a different animation.

I used this article to figure out how to have dynamic animations for my components, but unless I use history.push({pathname, state:{animation, duration}}) I don't see how I can specify a different animation to use when a user goes back.

Gabe O'Leary
  • 2,010
  • 4
  • 24
  • 41

1 Answers1

4

One solution could be to add a listen method to a custom history object for your app. Follow instructions here first to set it up.

Now, history.goBack() uses the POP action in the history stack, so you can check that like:

import { createBrowserHistory } from 'history';

const history = createBrowserHistory()

history.listen((location, action) => {
    if (action === 'POP') {
      history.replace(location.pathname, {specialAnimation: 'whatever value'});
    }
})

export default history

This way rewrites your state, if you have other stuff in your state you want you can do something like

location.state.specialAnimation = 'whatever';
4levels
  • 3,134
  • 1
  • 23
  • 22
izb
  • 562
  • 4
  • 11
  • 1
    thanks, this solution worked great (after a small fix to the syntax which I already edited above). – Gabe O'Leary Sep 26 '18 at 17:44
  • Bear in mind that if the user goes directly to the URL the action is also `'POP'` - so this approach doesn't work if you're trying to work out if 'back was pressed'. – Ian Grainger Jan 25 '22 at 11:52