I am seeking a solution for toggling a box (div) with slide-out animation and then sliding back in animation (in reverse) upon button press.
My requirement is to have no animations during the initial page render. While I can successfully slide the box to the left/fade out of the page on button press, the slide back in action lacks any transition or animation.
Is there a way to add this transition when the element reappears without introducing a class that triggers during the 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;
}
}