Animating slides with CSS Keyframes and React, incorporating toggle slide fade out and slide fade (back) in

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;
    }
}

JS Fiddle Link Here

Answer №1

the element does not smoothly return to its original state

In my quest for a solution to create an animation that reverts the element back after removing a keyframe, I came up empty-handed.
When using a keyframe, the animation from the initial state to the final state is crucial, making it difficult to achieve a seamless transition.

However, you can achieve your desired effect by utilizing a simple transition instead of relying on keyframes.
Simply include the new state within the .slideLeft class:

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

Additionally, apply the necessary transition properties to the .box:

.box {
  transition-duration: .5s;
  transition-property: transform, opacity;
}

I have made the changes in your JS Fiddle.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The expression req.files consistently comes back as an empty [object]

I have been encountering an issue with saving uploaded files using their original names (with express-fileupload). Whenever I upload a file, it gets saved in the directory as [object Object]. Node: var express = require('express') var app = exp ...

"I encountered an error while sorting lists in Vue 3 - the function this.lists.sort is not

Creating a Vue 3 front-end template: <template> <div class="container"> <router-link to="/user/create" class="btn btn-success mt-5 mb-5">Add New</router-link> <table class=" ...

Function exported as default in Typescript

My current version of TypeScript is 1.6.2 and we compile it to ECMA 5. I am a beginner in TypeScript, so please bear with me. These are the imported library typings. The contents of redux-thunk.d.ts: declare module "redux-thunk" { import { Middle ...

Accessing content from a text file and showcasing a designated line

Apologies if my wording was unclear... In this scenario, we will refer to the text file as example.txt. The value in question will be labeled as "Apple" My goal is to retrieve example.txt, search for Apple within it, and display the entire line where thi ...

Guide on sending emails with AngularJS and the Ionic framework

I have been attempting to send an email by using various links, but without success. I am looking for guidance on how to successfully send an email. Below is the code I have been using for sending emails. Any suggestions for changes would be greatly apprec ...

What steps should I take to set up a personalized prompt for user input in AngularJS?

After setting up the UI and scope variables, I am faced with a task that requires the function to only continue when either the left or right button is clicked (meaning $scope.isLeft or $scope.isRight will be true). This behavior is akin to how a regular J ...

I'm experiencing a lack of feedback while implementing jQuery/AJAX with JSONP

Attempting to perform a cross-domain request using jQuery/AJAX, I have the code below; $.ajax({ url: "http://www.cjihrig.com/development/jsonp/jsonp.php?callback=jsonpCallback&message=Hello", crossDomain:true }) .done(function( msg ) { alert( ...

What could be causing the reliability issue with this particular Angular JS code for dropdown menus?

Attempting to create a dynamic country-city dropdown menu using AngularJS <div> Country: </br> <select data-ng-model="country" ng-options="country.name for country in countries" data-ng-change="updateCountry(country) ...

Content that is dynamically generated by a database

I have been working on creating a unique wall feature for my website, inspired by Facebook. My aim is to allow users to submit form data and have it validated before storing it in a database. Additionally, I want this stored data to be displayed in a desig ...

What is the method for triggering the output of a function's value with specified parameters by clicking in an HTML

I am struggling to display a random number output below a button when it is clicked using a function. <!DOCTYPE html> <html> <body> <form> <input type="button" value="Click me" onclick="genRand()"> </form> <scri ...

The combination of HTML, CSS, and vertical text margins is essential for creating visually

Looking for some guidance on how html text and margins work? If there's a good online reference you can point me to, I'd greatly appreciate it! I'm currently struggling with setting precise margins for text. In the example below, there&apos ...

When downloading files in Chrome or Safari, the $ajax call is in a pending state, whereas in IE or Firefox,

Measuring the time it takes to download a 1MB file using AJAX calls. Below is the code snippet: var start = new Date(); $(document).ready(function() { $.ajax ({ url: 'https://www.example.com/dummyFile1024', crossDomain: t ...

What is the process for obtaining the source code for children in React?

Can React extract the source code from children props? Imagine having a component with the following structure... <SomeComp> <Heading>I want to access this code inside the Heading tag</Heading> </SomeComp> How can I retrieve t ...

I am puzzled as to why my code in React is rendering twice without any apparent reason

I ran into a strange issue where my console.log("hi") was being displayed twice. I was working on a simple todo-list project and noticed that everything was getting double clicked. After some troubleshooting, it seems like the code is executing any JavaScr ...

Struggling to bring in { useActionState } from 'react' while trying to follow the latest next.js tutorial with next.js v15.0.0-canary.28, react v19.0.0-rc, and types/react v18.2.21

Currently, I am following the tutorial on next.js available at https://nextjs.org/learn/dashboard-app I have reached chapter 14, which focuses on enhancing accessibility, located at https://nextjs.org/learn/dashboard-app/improving-accessibility During on ...

Can the lazy load script dependent on jQuery be utilized before the jquery.js script tag in the footer?

After receiving HTML from an AJAX callback, I noticed that there is a script tag for loading code that uses jQuery. However, I consistently encounter the error of jQuery being undefined. All scripts are connected before the closing </body> tag. Is ...

Position an image in the center and add a div below it

I am seeking guidance regarding two specific questions. My objective is to showcase an image in its true size while positioning it at the horizontal center of the screen (not the exact center), followed by a div containing text directly underneath the imag ...

Is there a way to use WithStyles<typeof styles> within Material UI?

import { WithStyles, createStyles } from '@material-ui/core'; const styles = (theme: Theme) => createStyles({ root: { /* ... */ }, paper: { /* ... */ }, button: { /* ... */ }, }); interface Props extends WithStyles<typeof styles> ...

Component built in ReactJS for file uploads to a server running on Spring MVC/Data-REST

For quite some time, I have been on the lookout for a ReactJS component that enables file uploading from a browser, with the ability to save it to the server where the ReactJS application is deployed. I've come across several components that facilita ...

Guide to utilizing jquery within node.js

Can anyone assist me with using jQuery in Node.js? I have the following code: const jsdom = require("jsdom"); const { JSDOM } = jsdom; const { window } = new JSDOM('<!DOCTYPE html>'); const $ = require('jquery')(window); var con ...