A few days ago I talked about server rendering with React Router, and yesterday I talked about using it on the client side to render components based on url path, for example, rendering the home page when the url is ‘/’ and the about page when the url is ‘/about’.
Today’s post is about how you can animate these changes.
Wrap the components you want to animate in ReactCSSTransitionGroup. Yesterday’s app component now looks like:
import React from 'react';
import ReactCSSTransitionGroup from 'react-addons-css-transition-group';
import Header from './Header';
class App extends React.Component {
render() {
return (
<div>
<Header />
<ReactCSSTransitionGroup
transitionName="example"
transitionEnterTimeout={500}
transitionLeaveTimeout={300}
>
{React.cloneElement(this.props.children, {key: page})}
</ReactCSSTransitionGroup>
</div>
);
}
}
export default App;
React’s cloneElement() lets you add a key to the child component passed by React Router — this is how React determines which children have entered, left or stayed.
There are a bunch of things you can animate with CSS, these classes use opacity to produce a fade-in effect:
.example-enter {
opacity: 0.01;
}
.example-enter.example-enter-active {
opacity: 1;
transition: opacity 500ms ease-in;
}
.example-leave {
opacity: 1;
}
.example-leave.example-leave-active {
opacity: 0.01;
transition: opacity 300ms ease-in;
}
That’s about it!
Doing something cool with React? Let me know!