I wanted to show the fade in effect for the text change on an element in ReactJS. I looked into ReactCSSTransitionGroup, and noticed it could not serve my need. ReactCSSTransitionGroup does very well animate the added and removed DOM node. If I just want to animate a text change without a DOM change, I will need to find a new solution.
Finally, here is my solution:
CSS
@-webkit-keyframes jump { 0% { opacity: 1; } 50% { opacity: 0 } 100% { opacity: 1; } } .jumpie { -webkit-animation-duration: 1s; -webkit-animation-iteration-count: 1; -webkit-animation-timing-function: linear; }
The parent component sending down the text change.
module.exports = React.createClass({ getInitialState: function () { return { counter: 0 }; }, componentDidMount: function () { var self = this; setInterval(function () { self.setState({ counter: self.state.counter + 1 }) }, 2000); }, render:function () { return (
); } })
The child element animates the text change.
import React from 'react';
module.exports = React.createClass({
getInitialState: function () {
return {
text: this.props.text
};
},
componentDidMount: function () {
React.findDOMNode(this.refs.jumpie).addEventListener('webkitAnimationEnd', function () {
this.style.webkitAnimationName = '';
});
},
componentWillReceiveProps: function (nextProps) {
var self = this;
if (nextProps.text !== this.props.text) {
React.findDOMNode(this.refs.jumpie).style.webkitAnimationName = 'jump';
setTimeout(function () {
self.setState({
text: nextProps.text
});
}, 500); //This is half the animation time we defined earlier in the CSS animation
}
},
render: function () {
return ({this.state.text});
}
});