Search code examples
animationlifecyclereactjsunmount

React lifecycle animations


I'm trying to find a way to perform animation depending of the ReactElement's lifecycle, it's pretty easy to do an animation when the component has just been mounted, but I would do another one before the component unmount.

I can't really use the ReactCSSTransitionGroup because that won't use RequestAnimationFrame.

Just to describe a bit my case, my component is a sidebar, that I can toggle on/off depending on some user's inputs.

var Sidebar = React.createClass({
    componentDidMount: function() {
        var menuUfeWidth = $('.menu-ufe').width();
        $(this.getDOMNode()).transition({x: menuUfeWidth}, Utils.animationDuration * 2, 'snap');
    },
    render: function() {
        return (
            <div className={'leaflet-sidebar left'}>
                <div className={'ufe-content'} />
            </div>
        );
    }
});

I am wondering how would you work your way off to be able to have an animation before the component unmount.


Solution

  • ReactCSSTransitionGroup is just a specialized version of ReactTransitionGroup that calls componentWillEnter, componentDidEnter, componentWillLeave, and componentDidLeave based on your defined CSS.

    If you don't want to use CSS animations, you can simply use ReactTransitionGroup and use a component that implements these lifecycle hooks using RAF-based animations:

    <ReactTransitionGroup component="div">
      <MyCustomReactTransitionComponent key={...} />
    </ReactTransitionGroup>
    

    Here's an example I found from another SO post: http://jsbin.com/jebumipimo/1/edit?html,console,output