Shindig: React Transitions with Stylus

Chet Corcos
2 min readNov 24, 2015

--

Defining the CSS for a React.addons.CSSTransitionGroup animation can be quite laborious. What’s even more annoying is when you want to swap out animations to compare them. CSS is notorious for not being DRY and that’s why we came up with CSS preprocessors.

Most people use CSS preprocessors just for nested styles, but LESS, SCSS, and Stylus all have some pretty powerful features that I don’t see people take advantage of enough. I think this is probably because they’re such awkward languages. Why hasn’t someone just some up with a way of writing CSS in a language we all know an love? — Coffeescript (and you thought I was going to say Javascript). I had a nice attempt at this but it was a major pain in the ass.

Regardless, we don’t want to write yet another CSS preprocessor, and since I’m such a big fan of Coffeescript, Stylus was a create choice for me. When I create my styles, I like to have a main file that contains all the parameters of my app so I can tweak everything from there. So my goal was to be able to specify animation from this main.styl file in a single line of code. I did this using Stylus functions. Here’s an example of a cross-fade animation definition.

animate-fade-in(name, action)
.{name}-{action}
opacity: 0
.{name}-{action}.{name}-{action}-active
transition: opacity .2s ease
opacity: 1
animate-fade-out(name, action)
.{name}-{action}
opacity: 1
.{name}-{action}.{name}-{action}-active
transition: opacity .2s ease
opacity: 0
animate-fade(name)
animate-fade-in(name, 'appear')
animate-fade-in(name, 'enter')
animate-fade-out(name, 'leave')

One quirk to watch out for is where you put the transition style. In the React documentation, they have it in the CSS class without the active class. This can cause problems where the element will animate to the initial style and not the active style.

Anyways, to use this, all I have to do is specify the transitionName I want to animate.

animate-fade('modal-backdrop')

And this the one-liner in my main.styl file. I have another stylus file that defines all kinds of animations and I can change animations easily just by calling a different function. And using Rupture, I can easily make these animations responsive as well.

+above(break)
animate-fade('navvc-push')
animate-fade('navvc-pop')
+below(break)
animate-push('navvc-push')
animate-pop('navvc-pop')

Next I’m going to explain how to get data into React components without using mixins. Much like the TabVC and NavVC, we’ll treat React components as high-order functions!

--

--