2

I have a child component where I would like to use slide-out animation as new props are getting passed to it and I try to use react-transition-group/switch-transition but is not really clear how to use it

The child component render method looks as it follows

return (
  <SwitchTransition mode="out-in">
    <CSSTransition
      classNames="slide"
    >
      <div className={classnames("fields-group", containerClass)}>
        {/* <pre>{JSON.stringify(this.props.fields, null, 2)}</pre>*/}

        {fields}
      </div>
    </CSSTransition>
  </SwitchTransition>
);
Mosh Feu
  • 28,354
  • 16
  • 88
  • 135
fefe
  • 8,755
  • 27
  • 104
  • 180

1 Answers1

3

There are more things you need to do:

  1. CSSTransition should has a prop key. When it changed, the transition will take affect.
  2. You need to add the transition styles by yourself because, React Transition Group is not an animation library like React-Motion, it does not animate styles by itself. reference

So the child component will look something like that:

function Child({ propToAnimate }) {
  return (
    <>
      <h4>Child Component</h4>
      <div className="main">
        <SwitchTransition mode="out-in">
          <CSSTransition
            key={propToAnimate}
            addEndListener={(node, done) => {
              node.addEventListener("transitionend", done, false);
            }}
            classNames="fade"
          >
            <div className="button-container">
              <div className="animate">
                <pre>state: {propToAnimate}</pre>
              </div>
            </div>
          </CSSTransition>
        </SwitchTransition>
      </div>
    </>
  );
}

And the styles (for slide animation for example):

.fade-enter .animate {
  opacity: 0;
  transform: translateX(-100%);
}
.fade-enter-active .animate {
  opacity: 1;
  transform: translateX(0%);
}
.fade-exit .animate {
  opacity: 1;
  transform: translateX(0%);
}
.fade-exit-active .animate {
  opacity: 0;
  transform: translateX(100%);
}
.fade-enter-active .animate,
.fade-exit-active .animate {
  transition: opacity 500ms, transform 500ms;
}

https://codesandbox.io/s/switchtransition-child-component-dk4jo

Mosh Feu
  • 28,354
  • 16
  • 88
  • 135