Animating A Simple react + redux Router

In a previous post created a simple react router that maintains it state using redux by using simple conditional rendering. While the technique works, it left something to be desired in the aesthetics department since screens transitioned without any animation.

However, react-native provides a simple way to fix this problem, LayoutAnimation. In addition to the official documentation, I recommend reading Justin Poliachik’s article “React Native’s LayoutAnimation is Awesome”. I used the techniques in the article to add some flair to the screen transitions in my application.

First I created a ScreenWrapper component that would actually be the component to be animated using the techniques described in Justin’s article. As you’ve probably guessed from the name, the ScreenWrapper component will wrap each screen of the application. The main difference is that ScreenWrapper renders the following:

render() {
return (
<View style={styles.wrapper}>
{this.props.component}
</View>
);
}

Passing the component is discussed next.

I attached the wrapper to each screen in a seperate file called “screens.js”. This file imports all the screens as well as the ScreenWrapper component. It’s main function is to step through the screens object from the previous post and wrap each component it contains inside of a ScreenWrapper like so:

// this object will hold the screens wrapped inside our animiatable component
let wrappedScreens = {};
Object.keys(screens).forEach((screenName, index) =>{
wrappedScreens[screenName] = {
screen: <ScreenWrapper
key={index}
component={screens[screenName].screen}
screenName={screenName} />
}
})

It is imperative that each wrappedScreen be given a key as an identifier, otherwise the ScreenWrapper will not receive the componentWillMount and componentWillUnmount life-cycle events that are required to fire the screen transition animations. You can read more about why from here.

Finally, as stated at the very beginning of the LayoutAnimation documentation you have to set some UIManager flags in order for the animation to work on Android. I just added the lines

if (Platform.OS === 'android') {
UIManager.setLayoutAnimationEnabledExperimental &&
UIManager.setLayoutAnimationEnabledExperimental(true);
}

To the same file that contained my highest component.

Reginald Johnson has maintained his passion for coding throughout his 20+ year career as an Officer in the United States Navy. He enjoys applying his training and experience in programming, Systems Engineering, and Operational Planning towards programming. Follow him Twitter @reginald3.