'Toggle slide fade out, slide fade (back) in with CSS Keyframes and React

I have a box (div) that I would like to toggle with slide-out animation and then slide-back in animation (the exact reverse) on button press.

I do not want any animations on initial page render. I am able to successfully slide the box left/fade-out of the page on button press, however the slide back in does not have any transition or animation.

How do I add this transition when the element comes back into view without adding a class that will fire with initial page render?

SlideBoxApp.js

class SlideBoxApp extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
        slideIn: false
    }
  }
  
  toggleSlide() {
    const { slideIn } = this.state
    this.setState({slideIn: !slideIn})
  }
  
  render() {
    const { slideIn } = this.state
      return (
        <div>
         <button onClick={() => this.toggleSlide()}>slide in</button>
         <div className={`box ${slideIn? 'slideLeft' : ''}`}></div>
        </div>
      )
   }
}

ReactDOM.render(<SlideBoxApp />, document.querySelector("#app"))

SlideBoxApp.css

body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

button {
  margin-bottom: 10px;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}

.box {
  width: 100px;
  height: 100px;
  background-color: pink;
}

.slideLeft {
  animation-duration: 500ms;
  animation-name: slideLeft;
  animation-fill-mode: forwards;
}

.slideRight {
  animation-duration: 500ms;
  animation-name: slideLeft;
  animation-fill-mode: forwards;
}

@keyframes slideLeft {
    0% {
        transform: translate(0, 0);
        opacity: 1;
    }

    100% {
        transform: translate(-100%, 0);
        opacity: 0;
    }
}

@keyframes slideRight {
    0% {
        transform: translate(0, 0);
        opacity: 0;
    }

    100% {
        transform: translate(100%, 0);
        opacity: 1;
    }
}

JS Fiddle Link Here



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source