Need Some Help Reversing the Direction of This CSS Mount Animation?

Exploring this fiddle, I encountered a small div showcasing an opacity animation. The animation smoothly executes when the state transitions to true upon mounting the component, causing the div to fade in beautifully. However, I faced a challenge as the animation fails to trigger when the component is unmounted and the state changes to false. Even after trying different approaches like setting the animation as both and attempting a reverse animation (from 1 to 0), it only ends up playing immediately following the initial one, resulting in the disappearance of the square.

Is there a way to ensure that this fade animation plays in reverse when the component disappears?

Edit: I omitted mentioning that this scenario is within React environment. Eventually, my workaround involved incorporating an animation library, simplifying the process significantly. Nonetheless, I am keeping this question posted in case others might have vanilla solutions to this issue.

Answer №1

I have come up with a clever workaround to resolve this issue. There may be a more elegant solution in the future, but for now, this will suffice.

To achieve this, I've defined a new class called .hide that adjusts the opacity to 0 and sets visibility to hidden. This class is then added to the box element. Initially, the insertion animation remains unchanged. However, for the exit animation, I've implemented a transition property on the box element. Upon a second click, I've encapsulated the setVisible() method within a setTimeout() function with a delay equal to the duration of the transition specified for .hide.

This approach ensures that the box fades out first before the setVisible() method is triggered afterwards.

If you prefer not to use setTimeout(), an alternative option is to attach an eventListener to the box for the transitionend event, and execute setVisible() once it has completed.

For demonstration purposes, I have provided a working demo on JSFiddle: https://jsfiddle.net/32y8vjus/1/

Note: In the JSFiddle example, I am altering the background color to illustrate the timing of the transition relative to the removal of the box. Feel free to modify this to work with opacity instead.

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

Display an error border around the TextField when the user clicks on the submit button

Utilizing material-ui's TextField component for my text field, I aim to display a red error outline if the required fields are left empty after the user submits. Most questions I've come across address scenarios where both the submit action and T ...

"Exploring the Possibilities of MUI v5: Elevate Your Bottom Navigation with a Styled

Previously, in Material-UI v4, I was able to use a StyledBadge within a BottomNavigationAction like this: <BottomNavigationAction id="0" label="Appointments" icon={( <StyledBadge badgeContent={numberOfUnreadAPP ...

What is the best way to determine if any of the objects in an array contain a "completed" property with a value of false using JavaScript and React?

Is there a way to determine if at least one item in an array of objects has a completed property with a value of false using JavaScript and React? Here is an example array of objects: const items = [ { id: "32", jobs: [ ...

Position the image in the exact center both vertically and horizontally

I am trying to center a list of images both vertically and horizontally within their respective li. I want to achieve this using jQuery. How can I align the images in the center of each li element both horizontally and vertically? You can view a demo at c ...

HTML5 allows users to play a extended video for a set duration without the need for any video editing. Users are encouraged to utilize any approach

I have a video file named myvideo.mp4 that is 3 minutes long (or any length). <video width="320" height="240" controls="controls"> <source src="myvideo.mp4" type="video/mp4"> </video> Is there a way to play this myvideo.mp4 for only 20 ...

I am unable to move HTML data to PHP

Here is my HTML code: <form action="test.php" method="get> <input type="text" name="text" /> </form> And this is my PHP code: <html> <head> <title>Result</title> </head> <body style="background: ...

NextJS React - WebpackError: Cannot access 'window' before initialization

I'm delving into the world of React and recently completed the "Getting Started" tutorial for NextJs (link), successfully setting up a new project. However, when attempting to import third-party plugins like current-devices or smooth-scrollbar, I enc ...

Tips for creating a cursor follower that mirrors the position and size of another div when hovering over it

I am trying to create a cursor element that follows the mouse X and Y position. When this cursor hovers over a text element in the menu, I want it to change in size and position. The size of the cursor should match the width and height of the text being h ...

What is causing the issue with this API request's functionality?

I have set up an API using Django-REST Framework and am currently working on connecting it to my frontend. One of the endpoints I created retrieves the last four winners, and when I test it, everything seems to be functioning properly. async function getL ...

Transitioning from the traditional LeftNav menu style to the more versatile composability feature using Reactjs with Material-ui

Hey there, I'm facing a bit of confusion while trying to create a LeftNav menu using material-ui. I recently joined this project and updated reactjs and material-ui. Unfortunately, many things related to LeftNav in material-ui have been deprecated, ...

What happens in the React tutorial when the clear fix is commented out and the appearance does not change?

Currently, I am working through the React tutorial and have encountered a question regarding their starter code: class Square extends React.Component { render() { return ( <button className="square"> {/* TODO */} </butto ...

How to Capture Clicks on Any DOM Element in React

Currently working on a web project using React and Node. My goal is to monitor all clicks across the entire document and verify if the previous click occurred within a 2-minute timeframe. ...

What is the best way to transfer the text from an input field into a paragraph when a button is

For a school project, I am developing a website focused on time management. My goal is to create an input text box that, when the "add task" button is clicked, transfers the text inside it to a paragraph or p2 element and then moves the input field down. ...

retrieve a string value from a function within a ReactJS component

I am facing an issue with returning a string from a function. Here is the function I am using: const getImage = (name) => { const imageRef = ref(storage, name); getDownloadURL(imageRef).then((url) => { return url; }); }; Even tho ...

Discover the method for measuring the size of a dynamically generated list

I'm currently working on a chat box that displays messages as a list. One issue I'm facing is that when I click on the start chat button, the chat box opens but the length of the list always remains zero. How can I resolve this problem? $(docu ...

Place a div on top of a table

I am facing a challenge with table rows and divs. The height of the table row is set to 100px, while divs can be up to 200px. I want the div to overlay the table and cover the bottom row if it exceeds the row's height. Currently, I have achieved this ...

Issue with rendering images on Bootstrap-Vue card component

In the process of creating a static website with Vue.js, I am attempting to incorporate a basic Bootstrap card using Bootstrap-Vue. Unfortunately, I am facing an issue where the image does not display when utilizing the b-card component with the img attrib ...

When an HTML element extends beyond the screen's right boundary, it becomes truncated

My website utilizes a table to showcase some data, but there's an issue when viewed on smaller screens. The table gets cut off and not all the content is visible. Even after scrolling completely to the right, the rightmost field remains barely visible ...

Can the outcomes be showcased again upon revisiting a page?

Whenever I navigate away from and return to my filter table/search page, the results vanish. I'm looking for a way to preserve the results without reloading the page. Essentially, I want the page to remain as it was originally, with the search results ...

Ways to Activate a Modal Using a Hyperlink

One of the features on my Next.js page is a modal that can be triggered by clicking a button: <button type='button' onClick={() => setOpen(true)}> The modal component looks like this: <Modal id='demo' show={isOpen} on ...