gabiseabra/styled-transition-group

How to use with react-router's <Switch>

axhamre opened this issue ยท 4 comments

Thanks for finally being able to define transitions with styled-components ๐Ÿ™‚

I'm struggling though a bit when I try to implement styled-transition-group with react-router, particularly it's Switch component.

Any hints on how these could work together?

styled-transition-group's components act pretty much the same as CSSTransition. Using TransitionGroup with Switch has always been tricky though, you have to get three details right:

  • The components go in this order: TransitionGroup > CSSTransition > Switch
  • You need to pass the location prop to Switch
  • And use that same location's key in CSSTransition

Here's a working example:
https://stackblitz.com/edit/01-styled-transition-group-rqmtoe?file=App.js

This is excellent, thank you so much!

Just an additional thought, if we'd like to have different transitions for each Route - would you scrap the <Switch> altoghether and go another route (no pun intended)?

How I now would customize transitions depending on which route is rendered would be to pass location.pathname as props to the styled-transition-group component. And then in the template literal part having ternary expressions, e.g. like this:

background: ${props => (props.pathname === '/editor') ? 'cyan' : 'green'};

But this feels a bit cumbersome, especially the styling part would be a bit messy with a lot of conditionals. Any ideas how to solve this in a better way would make my day ๐Ÿ˜Š

I can think of two ways you can achieve this.
You can use styled-components's css helper to keep each style separate from each other, which would be essentially the same thing you're doing with different semantics. Like:

import { css } from "styled-components"
import transition from "styled-transition-group"

const foo = css`/* ... */`
const bar = css`/* ... */`
const notFound = css`/* ... */`

const pickTransition = ({ location }) => {
	switch(location.pathname) {
		case "/foo": return foo
		case "/bar": return bar
		default: return notFound
	}
}

const MyTransition = transition.div`
	${pickTransition}
`

Or you can create an smart component to decide which transition should be rendered depending on the location. This would work even without styled-components. Here's a working example:

https://stackblitz.com/edit/01-styled-transition-group-v3j8ku?file=Transition%2Findex.js

Wow! This works 5x better than I ever wished for. Thank you! ๐Ÿ˜€