Search code examples
javascriptreactjsanimationreact-reduxreact-class-based-component

How to animate the disappearance of a component in ReactJS?


In my react App I have a class-based parent component Items. Inside it renders the child component Item.

export class Items extends Component {
    render() {
        return (
            <Fragment>
                <Filters />
                <div className="container__main">
                     this.props.items.map((item) => (
                          <Item key={item.id} item={item} />
                     ))
                </div>
            </Fragment>
        );
    }
}

and Item

export class Item extends Component {

    cmb = React.createRef();

    componentDidMount() {
        if (this.cmb.current !== null) {
            setTimeout(() => { 
                this.cmb.current.style.transform = "scaleY(1) translateZ(0)"; 
                this.cmb.current.style.transition = "all 0.5s ease-in-out"; });
        } else return;
    }

    render() {
        return (
            <div ref={this.cmb} className="someClass">
                // some code
            </div>
        )
    }
}

Each component Item is animated after it is mounted or re-mounted. But what is the best way to animate it when it disappears (if the parent component Items doesn't render it)?


Solution

  • TLDR

    As far as I know there is onAnimationStart, onAnimationEnd in React

    Answer

    You can use onAnimationStart, onAnimationEnd synthetic event listener and some props like isShowComponent, isHideComponent

    And you can use unmountComponentAtNode(), findDOMNode() in react-dom

    Peseudo Code

       handleAnimationEnd() {
         const node = ReactDom.findDOMNode(this);
         ReactDom.unmountComponentAtNode(node)
       }
       ...
       render(){
         return (
            <div onAnimtionEnd={this.handleAnimationEnd}>
            /** some code**/
            </div>
         )
       }
    

    ETC

    It is not real code but just peseudo! but I think you can do that using this api and event handler!
    Good luck!

    If you have any good solution. just hit me with comment!
    It should be helpful to other developer struggling with this issue

    Reference

    1. React Document
    2. React Dom Document
    3. code sandbox exmaple
    4. How to Trigger Animation Events using React