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;
}
}
CodePudding user response:
the slide back in does not have any transition or animation
I've searched for a solution to animate the element back to its original state after a keyframe is removed, and wasn't able to find one.
Having a keyframe means an animation between start and end states, so initial page animation is inevitable if you want to animate both in and out.
However, you could achieve your desired result with just transition instead of keyframes.
Just add the new state in .slideLeft class:
.slideLeft {
transform: translate(-100%, 0);
opacity: 0;
}
And give the .box some transition properties:
.box {
transition-duration: .5s;
transition-property: transform, opacity;
}
I updated your JS Fiddle.
