5

My code for setting up a Fade transition is the simplest :

import React from 'react';
import { Transition } from 'react-transition-group';
import PropTypes from 'prop-types';

const duration = 250;

const defaultStyle = {
  transition: `opacity ${duration}ms ease-in-out, color ${duration}ms ease-in-out`,
  opacity: 0,
}


const transitionStyles = {
  entering: { opacity: 0 },
  entered: { opacity: 1 },
  exiting: { opacity: 1 },
  exited: { opacity: 0 },
};


export default class Fade extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      in: false,
    };
  }

  componentDidMount() {
    this.setState({ in: true });
  }
  componentWillUnmount() {
    this.setState({ in: false });
  }

  render() {

    return(
      <Transition in={!!this.state.in} timeout={{ enter: 250, exit: 250, }} unmountOnExit={this.props.unmountOnExit || false} >
        {(state) => {
          return (
            <div 
              className={this.props.classes ? this.props.classes : ''} 
              style={{  ...defaultStyle, ...transitionStyles[state],}}>
              {this.props.children}
            </div>
          )
        }}
      </Transition>
    )
  }
}

Fade.propTypes = {
  classes: PropTypes.string,
};

Wrap any of your component within to try it out. I tried to build a snippet with it but I didn't succeed to build one with React, sorry about that.

My question : thanks to componentDidMount I can toggle the state of my component and make the fade in work perfectly. However, I struggle putting in place the fade out : using componentWillUnmount doesn't make it work.

What is the solution to my problem ? How should I delay the unmounting of the component in order to have the transition going on ?

arnaudambro
  • 2,403
  • 3
  • 25
  • 51

0 Answers0