Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define state when using `history.goBack()`

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.

like image 534
Gabe O'Leary Avatar asked Sep 25 '18 23:09

Gabe O'Leary


1 Answers

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';
like image 103
izb Avatar answered Nov 06 '22 02:11

izb