component:
import React, { PureComponent } from 'react'
import Lottie from 'react-lottie'
import animations from './animations'
import './Animation.css'
class Animation extends PureComponent {
static defaultProps = {
animation: '',
width: '100%',
height: '100%',
loop: true,
autoPlay: true,
}
constructor(props) {
super(props)
this.state = {
isStopped: !this.props.autoPlay,
isPaused: !this.props.autoPlay,
isComplete: false,
}
}
handleClick = () => {
this.setState({ isPaused: !this.state.isPaused })
}
handleEvent = (obj) => {
if (!this.props.loop) {
if (obj.currentTime === (obj.totalTime - 1)) {
if (this.state.isComplete) {
this.setState({ isStopped: true, isComplete: false })
} else {
this.setState({ isStopped: false, isComplete: true })
}
}
}
}
render() {
const animation = animations[this.props.animation]
const defaultOptions = {
loop: this.props.loop,
autoplay: this.props.autoPlay,
animationData: animation,
rendererSettings: {
preserveAspectRatio: 'xMidYMid slice',
}
}
const makeValidNumber = (value) =>
value.substr(value.length - 1) === '%' ? value : Number(value)
return (
<div className="Animation">
<Lottie
onClick={this.handleClick}
options={defaultOptions}
width={makeValidNumber(this.props.width)}
height={makeValidNumber(this.props.height)}
isStopped={this.state.isStopped}
isPaused={this.state.isPaused}
eventListeners={
[
{
eventName: 'enterFrame',
callback: obj => this.handleEvent(obj),
},
]
}
/>
</div>
)
}
}
export default Animation
You can always check the source code of this website too: Animation
There are many more cool examples in https://www.lottiefiles.com/ website!
Since we saw the goodness of Lottie web, let me tell you about one drawback I had to deal with recently. You know, it's good to be realistic about technical choices, not everything is flowers.
The case was: In a Meteor project I've been working on, I had to include an animation and our team decided to use Lottie web. The problem is that the library relies on window
object that's not available for SSR. Server-side rendering is a default feature on Meteor apps. Until the date of this post, this issue isn't resolved, although it's a known problem and I believe will be addressed soon.
As I told before, there are many ways to create interactive animations for the web and for this particular case I decided to go with CSS keyframes, the result went as expected, you can take a look here:
I hope to get back on animation topic much more often on future blog posts. I've been using several different approaches and still can't tell which one is the best. My guess is that there are cases and cases that will rely on different solutions. See ya!