Practical JS: Build your own React transition component
I’m going to resist my instinct to jump right into the code so we can first talk about motivation.
We’re using the fabulous material-ui
and we needed to animate items as they enter a list. MUI has some built-in transition components that work well and look great, but they weren’t really what we needed (our very talented UX designer had a very clear vision of what she wanted and not one of them was quite it). Ah! An opportunity to build my own, and learn something new.
The way we are going to animate components into view is by using react-transition-group
and building a <Transition>
component. A Transition
component has a very simple lifecycle; we attach a style to each lifecycle phase as needed, and BAM, we have a transition component ready to go. I can resist no more, so here’s the complete code to a component that transitions components into view with a blink.
Let’s break this down.
transitionStyles
contain style per lifecycle phase. The lifecycle is entering → entered → exiting → exited
, so when you name your styles accordingly, each style is used in the corresponding phase. It’s really that simple.
In this case, I only wanted animation when coming into view, so I had no need for the other phases. The rest of the work is just composing external styles that may have been used with our transition styles, and we’re done. Easy peasy.
The final result looks like this
Now go write your own and create some fabulous transitions.