React-transition-group tweening and js animation
Useful for page transitions in React, or just animating in and out parts of your UI in javascript without pre-defined timeout, this method finally makes Javascript animation in React sane.
Extend the Transition component and wrap it in some custom logic which enables you to control the ending of your animation dynamically via the addEndListener
prop.
export default class CustomTransition extends React.Component {
constructor(props) {
super(props);
this.currentTransition = Promise.resolve(true);
}render() {
const { onEnter, onExit, ...props } = this.props;
return (
<Transition
{...props}
onEnter={(...onEnterProps) => {
this.currentTransition = onEnter(...onEnterProps);
}}
onExit={(...onExitProps) => {
this.currentTransition = onExit(...onExitProps);
}}
addEndListener={(node, done) => {
this.currentTransition
.then(done);
}}>
{props.children}
</Transition>
);
}
}
Use as a normal <Transition>
component.
<SwitchTransition> // or <TransitionGroup>
<CustomTransition key={…} onEnter={..} onExit={…}>
<SomeComponentHere />
</CustomTransition>
</SwitchTransition>
Example of onEnter
/ onExit
using GSAP:
const onExit = el => {
return gsap.to(el, {
duration: 0.3,
x: -300
});
};
You can of course use any animation framework as long as you return a promise which resolves when your animation is finished.
If there are any questions, feel free to leave a comment below and I’ll do my best to explain and expand the article to make the solution more clear.