5

I want to make left and right slide with react-transition-group. When I press next button it comes right (next step) and when I click go back button, I want to come it from left. My code always gets it from right side. How can I achieve something like this

.onboarding-screen
    display flex
    flex-direction column
    flex-grow 1
    position absolute
    width 100%
    height 100%
    align-items center
    &.step-enter
        transform translateX(100%)
        transition(all 1s)
    &.step-enter-active
        transform translateX(0%)
        transition(all 1s)
    &.step-enter-done
        position relative
    &.step-exit
        transform translateX(-100%)
        transition(all 1s)
    &.step-exit-active
        transform translateX(-100%)
        transition(all 1s)
    &.step-exit-done
        position relative
edwardthatch
  • 69
  • 1
  • 5

1 Answers1

9
  • First of all you don't need -done variations,
  • Your css only handles the the animation when you click the next button (enters from right, exits from left), therefore you also need the opposite of that:

CSS:

.right-to-left-enter {
    transform: translateX(100%);
}
.right-to-left-enter-active {
    transform: translateX(0);
    transition:all 1s ease;
}      

.right-to-left-exit {
    transform: translateX(0);
}
.right-to-left-exit-active {
    transform: translateX(-100%);
    transition:all 1s ease;
}      

.left-to-right-enter {
    transform: translateX(-100%);
}
.left-to-right-enter-active {
    transform: translateX(0);
    transition:all 1s ease;
}      

.left-to-right-exit {
    transform: translateX(0);
}
.left-to-right-exit-active {
    transform: translateX(100%);
    transition:all 1s ease;
}      

You need TransitionGroup and CSSTransition for the sliding animation you want. However there is one thing to note:

Once a CSSTransition is mounted, you can not alter the exit animation even if you change the classNames property on the go. But there is a property called childFactory of TransitionGroup component which gives you the ability yo change the mounted CSSTransition component's properties.

Here is the code you need:

const [isNext, setIsNext] = useState(true);

const onNext = () => setIsNext(true);
const onPrevious = () => setIsNext(false);

return (
<TransitionGroup childFactory={child => React.cloneElement(child, { classNames: isNext ? "right-to-left" : "left-to-right", timeout: 1000 })}>
    <CSSTransition key={key} classNames="right-to-left" timeout={1000}>
          // Put your sliding content here. Change the key as the content changes.
          // The value of the key is unimportant
    </CSSTransition>
</TransitionGroup>
);

Do not forget to use absolute positioning on sliding content

semihlt
  • 136
  • 5
  • question here, https://stackoverflow.com/questions/75797699/react-transition-group-without-separate-css-classes – mattsmith5 Mar 21 '23 at 05:51