CSS Transitions can make your app / website look professional. Back in the jQuery days, this was easy. With React, it’s mounted or it’s not. Components snap in place abruptly, instead of gently easing in.

There are lots of resources and complicated ways to go about this. However, if you want a quick DIY, here’s an overview using 2 core principles:

CSS animations Higher Order Components

The CSS code enabling the transitions:

.fade-in {

opacity: 0;

}

.fade-in.visible {

transition: opacity 1s ease-in;

opacity: 1;

}

What’s happening here is we have one state, opacity: 0 and need to switch to another state, opacity: 1 . The transition: opacity 1s ease-in; informs the opacity how to do this.

The React code:

import React from 'react'; const AnimateLoad = (WrappedComponent) => {

return class extends React.Component {

state = {didMount: false}

componentDidMount(){

setTimeout(() => {

this.setState({didMount: true})

}, 0)

}

render(){

const {didMount} = this.state

return (

<div className={`fade-in ${didMount && 'visible'}`}>

<WrappedComponent {...this.props} />

</div>

);

}

}

}

As you can see, the AnimateLoad wraps a component and returns it, after manipulating the class names on mount. The setTimeout in componentDidMount is necessary, because it defers adding the ‘visible’ class until after the mount has happened. This means it goes from fade-in to fade-in visible and allows the transition to happen. Alternatively, something like the following will not work:

componentDidMount() { this.setState({didMount: true}) }

This will render both classes, fade-in and visible on mount, not giving the CSS a chance to do its thing.

To put it all together:

@AnimateLoad

class SomeComponent extends React.Component {

return <div>Hello World</div>

} class SomeComponent extends React.Component {return Hello World

As you can see, AnimateLoad is a Higher Order Component, returning SomeComponent. The transition happens in the CSS on mount. All this, and you get the following result:

The use case here is for simple component loading, but the formula is only limited by your imagination. Thanks for reading!

Note: This code is useful for illustrating some neat aspects of React and a quick and dirty way to animate components, but there are officially sanctioned methods on the React site, as written by Joe Davis and a number of animation libraries available.