javascriptcssreactjscss-transitionsreactcsstransitiongroup

React CSSTransition not animating


I want to animate a box (fade-in, fade-out) in my web app. I am using react-transition-group for this. But somehow, the animation is not working. Code

import React from 'react';
import ReactDOM from 'react-dom';
import { CSSTransition } from 'react-transition-group';
import Modal from 'react-modal';

import './styles.css';

class Example extends React.Component {
  state = {
    isOpen: false,
  };

  toggleModal = () => {
    this.setState(prevState => ({
      isOpen: !prevState.isOpen,
    }));
  };
  render() {
    const modalStyles = {
      overlay: {
        backgroundColor: '#ffffff',
      },
    };
    return (
      <div>
        <button onClick={this.toggleModal}>
          Open Modal
        </button>
        <CSSTransition
          in={this.state.isOpen}
          timeout={300}
          classNames="dialog"
        >
          <Modal
            isOpen={this.state.isOpen}
            style={modalStyles}
          >
            <button onClick={this.toggleModal}>
              Close Modal
            </button>
            <div>Hello World</div>
          </Modal>
        </CSSTransition>
      </div>
    );
  }
}

CSS:

.dialog-enter {
  opacity: 0;
  transition: opacity 500ms linear;
}
.dialog-enter-active {
  opacity: 1;
}
.dialog-exit {
  opacity: 0;
}
.dialog-exit-active {
  opacity: 1;
}

.box {
  width: 200px;
  height: 100vh;
  background: blue;
  color: white;
}

Here is the working code. Click on "Open Modal" to open the modal and then click on "Toggle Box" to open/close the box which I want to animate.

EDIT: I am actually trying to get the box slide-in and slide-out when toggled. Here is

the updated CSS:

.dialog-enter {
  left: 100%;
  transition: left 1500ms;
 }
.dialog-enter-active {
  left: 0;
}
.dialog-exit {
  left: 0;
  transition: left 1500ms;
}
.dialog-exit-active {
  left: 100%;
}

.box {
  position: absolute;
  width: 200px;
  height: 50vh;
  background: blue;

Updated code link


Solution

  • You have to trust the mount/unmount to the CSSTransition entirely.

      <CSSTransition
        in={this.state.boxVisible}
        timeout={1500}
        classNames="dialog"
        unmountOnExit
      >
        <div>
          <div className="box">Box</div>
        </div>
      </CSSTransition>
    

    See here: https://codesandbox.io/s/csstransition-component-9obbb

    UPDATE: If you want to move an element with the left css property as you asked in the comment. You must add the position: realative style to it as well.

    .dialog-enter {
      left: 100%;
      transition: left 1500ms;
      position: relative;
    }
    .dialog-enter-active {
      left: 0;
    }
    .dialog-exit {
      left: 0;
      transition: left 1500ms;
      position: relative;
    }
    .dialog-exit-active {
      left: 100%;
    }