P
P
Pavel Antonov2018-12-14 15:54:18
React
Pavel Antonov, 2018-12-14 15:54:18

How do you animate component mount/unmount in react?

I use styled-components, but the question is also relevant for ordinary components, since the principles for using components do not differ much.
I'm looking for an adequate way to animate the appearance and disappearance of components in the DOM, tell me who uses what?
So far I have settled on styled-transition-group

Using a simple Modal as an example, I will show how I use it (Spoiler with code)
// Modal.jsx
import React from 'react';

import {
    Modal as StyledModal
} from './styled';

/** Модальное окно */
export const Modal = ({
  open = false
} = {}) => (
  <StyledModal unmountOnExit in={open} timeout={300}>
    {children}
  </StyledModal>
)

// styled.jsx
import transition from 'styled-transition-group';

export const Modal = transition.div`
  display: flex;
  align-items: center;
  background: #fff;
  position: fixed;
  top: 50%;
  left: 50%;
  max-width: 765px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 5px 15px rgba(0,0,0,.5);
  transform: translateX(-50%) translateY(-50%) perspective(600px) rotateX(0);
  padding: 45px 70px;
  transition: all 0.3s ease;
  z-index: 1110;
  line-height: normal;
  &:enter {
    opacity: 0;
    transform: translateX(-50%) translateY(-70%) perspective(600px) rotateX(10deg);
  }
  &:enter-active {
    opacity: 1;
    transform: translateX(-50%) translateY(-50%) perspective(600px) rotateX(0);
  }
  &:exit {
    opacity: 1;
    transform: translateX(-50%) translateY(-50%) perspective(600px) rotateX(0);
  }
  &:exit-active {
    opacity: 0;
    transform: translateX(-50%) translateY(-70%) perspective(600px) rotateX(10deg);
  }
`;

In principle, everything suits, but as always there are downsides.
We use a wrapper called Showable
Showable.jsx Code
// Showable.jsx
import React from 'react';

const Showable = WrappedComponent => class extends React.PureComponent {
    render() {
      const { isShow } = this.props;
      if (!isShow) {
        return null;
      }
      return (
        <WrappedComponent
          {...this.props}
        />
      );
    }
};

export default Showable;

If the component is wrapped in a HOC, then for some reason the mount and unmount stops being animated. In principle it is clear why, Showable returns null if the component is not needed on the page, but when the component is needed Showable becomes true the component appears, but without animation.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question