Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Navigation direction aware #94

Open
bitttttten opened this issue May 21, 2018 · 1 comment
Open

Navigation direction aware #94

bitttttten opened this issue May 21, 2018 · 1 comment

Comments

@bitttttten
Copy link

Is it possible to make the AnimatedSwitch component aware of the direction the navigation is? For example, when going back (by using the back button in the browser) I would like a different animation and styling than when user is navigating forward.

@lcamargof
Copy link

lcamargof commented Jan 22, 2020

You can use another component as a wrapper and control your animation direction.

This is an example of my component:

const RIGHT = {
  atEnter: { offset: 100, opacity: 0 },
  atLeave: { offset: -100, opacity: 0 }
}

const LEFT = {
  atEnter: { offset: -100, opacity: 0 },
  atLeave: { offset: 100, opacity: 0 }
}

class SlideSwitch extends PureComponent {
  constructor (props) {
    super(props)

    this.prevPath = props.location.pathname
    this.currentPathIndex = props.routes.indexOf(window.location.pathname)
    this.currentAnimation = RIGHT
  }

  render () {
    const { match, location, history, children, routes, ...props } = this.props

    if (this.prevPath && location.pathname !== this.prevPath) {
      const routeIndex = routes.indexOf(location.pathname)

      if (history.action === 'POP') {
        this.currentAnimation = LEFT
      } else if (routeIndex === -1 || routeIndex > this.currentPathIndex) {
        this.currentAnimation = RIGHT
      } else {
        this.currentAnimation = LEFT
      }

      this.currentPathIndex = routeIndex
      this.prevPath = location.pathname
    }

    return (
      <AnimatedSwitch
        {...this.currentAnimation}
        atActive={{ offset: 0, opacity: 1 }}
        mapStyles={(styles) => ({
          transform: `translateX(${styles.offset}%)`,
          opacity: styles.opacity
        })}
        {...props}
      >
        { children }
      </AnimatedSwitch>
    )
  }
}

where routes is an array of my routes ordered correctly
Of course, this is a naive implementation, you will need to use something more advanced (like a regex) to match the routes if you have like wildcards or parameters on the route.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants