React Component Transitions with Slide-Up Effect

Recently, I've been experimenting with incorporating animations and transitions into my React.js projects. In the animated GIF provided below, you can see that when I close a Message component, it smoothly fades out. Once the fade out animation completes, I then hide the component using onAnimationEnd.

My goal is to have the Components below slide up when a Message disappears. I'm currently exploring how to achieve this conceptually, whether through a CSS animation/transition approach or a React-specific method.

https://i.sstatic.net/zfRQI.gif

Message.js

import React, {PropTypes, Component} from 'react';
import MessageTypes from '../constants/MessageTypes';

export default class Message extends Component {

    constructor(props, context) {
        super(props, context);
        this.handleClick = this.handleClick.bind(this);
        this.onAnimationEnd = this.onAnimationEnd.bind(this);
        this.state = {
            animate: false,
            hide: false
        }
    }

    handleClick(e) {
        e.preventDefault();
        this.setState({animate: true});
    }

    onAnimationEnd() {
        console.log('fdsfd');
        this.setState({hide: true});
    }

    render() {
        return (
            <div ref="message" onAnimationEnd={this.onAnimationEnd} className={`card message ${this.state.hide ? 'hide open' : ''} ${this.state.animate ? 'message-transition-fade-out' : ''}`}>
                <span className={`icon icon-${this.iconLevel()}`} style={{color: `#${this.iconColor()}`}}></span>
                <p>
                    <strong>{this.props.title}</strong><br />
                    <span dangerouslySetInnerHTML={{ __html: this.props.message }} />
                </p>
                <a href="#" onClick={this.handleClick}>
                    <span className="icon icon-close"></span>
                </a>
            </div>  
        );
    }

}

Message.scss

.message {

    max-height: 150px;
    transition: height 2s ease;

    &.open {
        height: 0; //define your height or use max-height
    }

    &-transition {

        &-fade-out {

            @include animation(0s, .3s, fadeout);

        }

    }
}

Answer №1

To achieve the desired effect, I recommend utilizing css transitions.

Create a class named expand and apply it to the main element of the MessageBox component. Upon onAnimationEnd, remove the expand class. Utilize the height property for animating this class.

Sample code snippet.

.messageBox {
 height: 0px;
 transition: height 0.3s ease;
}

.messageBox.expand {
  height: 100px; //specify the desired height or use max-height  
} 

Answer №2

If you're looking to implement collapsible content in your React application, you can use the npm module called react-collapse to do the trick.

<Collapse isOpened={this.state.isOpened} keepCollapsedContent={true}>
     //content here
</Collapse>

Check out the results below:

https://i.sstatic.net/AffIq.gif

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

Ensure that every HTML link consistently triggers the Complete Action With prompt on Android devices

After extensive searching, I have yet to find a solution to my issue. I have been developing a web application that allows users to play video files, primarily in the mp4 format. Depending on the mobile browser being used, when clicking the link, the vide ...

Positional vs Named Parameters in TypeScript Constructor

Currently, I have a class that requires 7+ positional parameters. class User { constructor (param1, param2, param3, …etc) { // … } } I am looking to switch to named parameters using an options object. type UserOptions = { param1: string // ...

The file field appears to be empty when sending a multipart/form-data request via AJAX

I'm encountering an issue when attempting to submit a multipart/form-data using AJAX. Here is the HTML code snippet: <form id='form_foto' method='post' enctype='multipart/form-data'> <input type='hidden ...

Submit a set of form variables to PHP using AJAX

I am attempting to transmit a set of form parameters to a PHP script for processing. In the past, I have achieved this using $.post, but now my goal is to accomplish it exclusively with $.ajax. Below is the jQuery click event designed to send all variabl ...

Is there a way for a DOMWindow popup to automatically resize to fit its

Currently exploring JQuery and learning on the fly, I'm wondering if there's a method to automatically adjust the size of a DOM window based on its content? I've successfully modified the parameters to accept % width and height instead of p ...

Is there a way to access multiple values from my function array in Javascript instead of just the first one?

function findDistinctElements(inputArray) { let distinctItems = []; for (let i = 0; i < inputArray.length; i++) { const currentItem = inputArray[i]; if (!distinctItems.includes(currentItem)) { console.log(`Argument ${i+1}: $ ...

Incorporate a Burger Icon into the Navigation Menu

insert image description here I am currently working on implementing a hamburger slide-out feature in my navigation bar. The desired behavior is for the sidebar to slide out to the right. We are using Elementor within WordPress for this project. Has anyone ...

Looping through images using JQuery

I'm struggling with an image animation and can't quite figure out how to make it work. <div id="img_loop"> <img src="img/img1.jpg" alt="image1" /> <img src="img/img2.jpg" alt="image2" class="hidden" /> <img src="im ...

Manipulating a 2D array in Javascript and Jquery: Implementing push functionality

I am trying to set up an array structure as follows: track[divID][wrapID] However, when I attempted track[divID][wrapID] = wrapID, I encountered an issue. This is because I need to add more elements to the second dimension in another loop, like this: tr ...

What is preventing my image from moving upwards?

I've been struggling to move this image up, despite trying several methods. I really want it to be aligned horizontally with the PV picture. I need the HP image to be moved directly upwards so that it aligns horizontally with the PV image. This is t ...

Issue with Local Storage: Value not being saved, instead [object MouseEvent] being stored

I am truly grateful for the help from @zim as it allowed me to drastically simplify my code for 2 buttons that store true/false values locally. However, I am facing an issue where the button click is registering as [object MouseEvent] instead of True/False ...

What is the best method for aligning buttons in a row with all the other buttons?

I have been attempting to display two buttons, id="strength" and id="minion", when a certain button, id="expandButton", is clicked. I want these two buttons to be positioned on either side of the button that triggers their cre ...

Discovering the channel editor on Discord using the channelUpdate event

While working on the creation of the event updateChannel, I noticed that in the Discord.JS Docs, there isn't clear information on how to identify who edited a channel. Is it even possible? Below is the current code snippet that I have: Using Discord. ...

Instructions on how to dynamically update a form field based on the input in another field using conditional statements

I'm seeking advice on how to automatically update a field based on user input without the need for manual saving. For example, if the user types '95' in the input field, the equivalent value displayed should be '1.0' in real-time. ...

Ways to append each list item from one unordered list to the end of another based on their unique styles

I am in the process of making a website responsive and I am faced with the task of combining two different menus. In order to achieve this, I need to transfer all list items (li) from one unordered list (ul) to another. Provided below is a simplified vers ...

What is the best way to link function calls together dynamically using RXJS?

I am seeking a way to store the result of an initial request and then retrieve that stored value for subsequent requests. Currently, I am utilizing promises and chaining them to achieve this functionality. While my current solution works fine, I am interes ...

Failing to reach the nested if statements within a switch case block

Before removing my question, please read this. Despite testing with console.logs, my code does not enter the if statements. I have not come across a similar solution to my issue. In an attempt to address any timing or asynchronous problems, I added a use ...

Creating an animated transition for an element's height with CSS

I need to animate the height of a div that doesn't have a specified height. Using max-height isn't an option due to multiple potential height amounts. I attempted adding transition: height 0.2s ease to the div, but it didn't work as expecte ...

Adding new elements to a list with Jquery, seamlessly integrating them without the need to

I am facing a bit of a roadblock in figuring out how to achieve this, mainly due to my limited understanding of JavaScript. The code that I have been looking at is as follows: http://jsfiddle.net/spadez/VrGau/ What I am attempting to accomplish is allowi ...

javascript: obtain the height of the pseudo :before element

Can someone help me figure out how to get the height of a pseudo :before element? I've tried using jQuery but it's not working as expected. Here's what I attempted: $('.test:before').height() // --> null If you want to take a ...