SwitchTransition

A transition component inspired by the vue transition modes. You can use it when you want to control the render between state transitions. Based on the selected mode and the child's key which is the Transition or CSSTransition component, the SwitchTransition makes a consistent transition between them.

If the out-in mode is selected, the SwitchTransition waits until the old child leaves and then inserts a new child. If the in-out mode is selected, the SwitchTransition inserts a new child first, waits for the new child to enter and then removes the old child.

Note: If you want the animation to happen simultaneously (that is, to have the old child removed and a new child inserted at the same time), you should use TransitionGroup instead.

function App() {
 const [state, setState] = useState(false);
 const helloRef = useRef(null);
 const goodbyeRef = useRef(null);
 const nodeRef = state ? goodbyeRef : helloRef;
 return (
   <SwitchTransition>
     <CSSTransition
       key={state ? "Goodbye, world!" : "Hello, world!"}
       nodeRef={nodeRef}
       addEndListener={(node, done) => node.addEventListener("transitionend", done, false)}
       classNames='fade'
     >
       <button ref={nodeRef} onClick={() => setState(state => !state)}>
         {state ? "Goodbye, world!" : "Hello, world!"}
       </button>
     </CSSTransition>
   </SwitchTransition>
 );
}
.fade-enter{
   opacity: 0;
}
.fade-exit{
   opacity: 1;
}
.fade-enter-active{
   opacity: 1;
}
.fade-exit-active{
   opacity: 0;
}
.fade-enter-active,
.fade-exit-active{
   transition: opacity 500ms;
}

Example

Props

mode

Transition modes. out-in: Current element transitions out first, then when complete, the new element transitions in. in-out: New element transitions in first, then when complete, the current element transitions out.

type: 'out-in'|'in-out'
default: 'out-in'

children

Any Transition or CSSTransition component.

type: element