By Kevin Hou
3 minute read
Historical Note: The code examples in this 2015 post target early React versions. They rely on the legacy React.createClass syntax (deprecated in version 15.5 and removed in 16.0) and basic manual DOM state-toggling. For modern implementations, use functional components with React Hooks (useState), paired with dynamic CSS class management or dedicated animation libraries.
I've been working with CSS3 animations lately, primarily to add motion and excitement to my project. I've played around with them and I've figured out the basics with entrances, exits, transitions, scaling, etc. The method that I've been doing is essentially using a state as a boolean. If a button is clicked, the state is toggled and the animation class is added onto the div container. It looks something like this (most of this code is courtesy of Seimith Suth):
1module.exports = React.createClass({
2 getInitialState() {
3 return {
4 animate: false
5 }
6 },
7 buttonClick() {
8 console.log(this.state)
9 this.setState({
10 animate: !this.state.animate
11 })
12 },
13 render() {
14 var className = this.state.animate ? "bump" : "";
15 return (
16 <div>
17 <button onClick={this.buttonClick.bind(this)}>Button</button>
18 <div className="animation">
19 <div className={"truck " + className}>
20 <img src="https://upload.wikimedia.org/wikipedia/commons/f/f9/Salesforce.com_logo.svg" />
21 </div>
22 </div>
23 </div>
24 )
25 }
26});
27
1@-webkit-keyframes bounce { 2 0% { 3 -webkit-transform: translateX(0px); 4 } 5 30% { 6 -webkit-transform: translateX(50px); 7 } 8 60% { 9 -webkit-transform: translateX(-45px); 10 } 11} 12 13.animation { 14 display: flex; 15 position: fixed; 16 /*top: 50%; 17 left: 45%;*/ 18} 19.animation .truck { 20 width: 50px; 21 height: 50px; 22 opacity: 1; 23 transform: scale(1); 24 box-shadow: none; 25 transition: all 300ms ease-in-out; 26} 27 28.animation .bump { 29 /*Need webkit for codepen here for some reason*/ 30 -webkit-animation-name: bounce; 31 -webkit-animation-iteration-count: 1; 32 -webkit-animation-duration: 800ms; 33} 34
The problem with this, is that the button simply toggles between true and false. There is no elegant way to set the state back to false after the animation is done. However, there are some alternatives:
In my opinion, the easier solution would be simply to use a setTimeout function to automatically run a function that sets the state as false after a given amount of time. Simply set the interval to be equal to or longer than the animation and it should work. Simple!
The second way is to use jQuery. I'm no expert on jQuery so I'll let Google do the work for me. I know a lot of people were posting about it so I figured there is a solution.
Hope this helped!