Open bitttttten opened 6 years ago
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.
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.