I\'d like to animate between two components where the first component fades out and is removed from the DOM before the next component is added to the DOM and fades in. Other
Solved using the componentWillUnmount() lifecycle method.
http://jsfiddle.net/phepyezx/9/
Here's the code:
var ReactCSSTransitionGroup = React.addons.CSSTransitionGroup;
const Off = React.createClass({
componentWillUnmount () {
this.props.handleTransitionEnd();
},
render() {
return (
OFF
)
}
});
const On = React.createClass({
componentWillUnmount () {
this.props.handleTransitionEnd();
},
render() {
return (
ON
)
}
});
var Switch = React.createClass({
getInitialState: function() {
return {
on: false,
transitionEnd: true
};
},
toggle: function(e) {
this.setState({
on: !this.state.on,
transitionEnd: false
});
},
handleTransitionEnd() {
this.setState({transitionEnd: true});
},
renderOff() {
if (! this.state.on && this.state.transitionEnd) {
return (
)
}
},
renderOn() {
if (this.state.on && this.state.transitionEnd) {
return (
)
}
},
render: function() {
return (
{this.renderOff()}
{this.renderOn()}
);
}
});
React.render( , document.getElementById("switch"));
And the relevant css:
.switch-enter {
opacity: 0.01;
}
.switch-enter.switch-enter-active {
opacity: 1.0;
transition: opacity 500ms ease-in;
}
.switch-leave {
opacity: 1.0;
}
.switch-leave.switch-leave-active {
opacity: 0;
transition: opacity 500ms ease-out;
}
You can achieve the same effective result with Jonny Buchanan's answer which uses absolute positioning and a delay instead of componentWillUnmount()