Animating with React
I’ve been using React now for a little over a year, and it’s safe to say I absolutely love it. Even though the development times are still slightly longer than your standard Wordpress build, it’s a new and exciting technology that is maturing and growing in ways which we aren’t yet aware of.
One of the biggest stumbling blocks for a lot of developers, though, is how to successfully animate. When using a routing solution like React Router (we’ll call it RR moving forward), you’re instantly presented with an issue; on route change, everything in the DOM gets removed and new DOM elements are injected, especially if you’re using RR in your top ‘container component’.
The instant assumed fix is to look at things like ReactTransitionGroup, which add a load of extra methods like:
Whilst these are great additions, the animations consistently looked a bit, well, average. Things seem to jerk on and off the page, and if you wanted to do some complex animations you were a bit stuck.
What I came to realise, is that, for it’s positives RR has one massive flaw. It removes the SPAness of the framework. You’re simply swapping out the entire page on route change which isn’t really what was intended of React or any other framework.
The reliance of RR in this situations had taken us down a dark path, one where we couldn’t use state to our advantage.
I started messing around with this a bit in our framework. I asked the question, what if we only used RR for actually handling the navigation, and giving back elements their option of having multiple states, and existing in many places?
Here’s a quick example. You have a website. The homepage most likely has a card-like view which contains a news story. Inside that component there is an image block, a title, a short description and a link.
Now, imagine if you will the physical news page. That has an image, a title, that same short description and then a large block more text.
Can you see the similarities? The only difference in some ways is where the component is and the CSS styling of some of the elements. With this in mind you can feel empowered to utilise the React State tree in the way in which it was (possibly) intended. This also opens up avenues for you having elements constantly on a page when they need to be.
The approach I took
I decided to take a break from tradition. Although I still use RR in all of my projects I feel that having a separate component which I’ve named a ‘control component’ which is essentially just a switch statement that responds to various page routes.
Inside each condition on the statement is a simple setState function, which enables or disables components, and passes various values. Then inside each component, the values which get modified in the props are used to update classes. This makes it super easy to modify styles using CSS animations!