Transition smoothly between components in React using CSS transitions with TransitionGroup

I am currently working on a small quiz application where child components (representing questions) are being swapped in. My goal is to add animated transitions between the component swaps using ReactCSSTransitionGroup.

To achieve this, I have created a function that renders the components and wraps them in a ReactCSSTransitionGroup like this:

render() {
  return (
    <div className=" questions-container">
      <ReactCSSTransitionGroup transitionName="switch">
        {this.renderQuiz(step)}
      </ReactCSSTransitionGroup>
    </div>
  );
}

The renderQuiz function essentially contains a switch statement that determines the correct component based on the current state, which looks something like this:

renderQuiz(step) {
  switch (step) {
    case 0:
      return (
        <StepZero />
      );
    case 1:
      return (
        <StepOne />
      );
    ....
  }
}

'Step' here refers to a local component variable (this.state.step). While I can see the first component fading in when it loads, there seems to be an issue with transitioning between the component switches.

Below is the CSS code related to the transition effects:

.switch-enter {
  opacity: 0.01;
}

.switch-enter.switch-enter-active {
  opacity: 1.0;
  transition: opacity 500ms ease-in;
}

.switch-leave {
  opacity: 1.0;
}

.switch-leave.switch-leave-active {
  opacity: 0;
  transition: opacity 500ms ease-out;
}

I am currently struggling to make these transitions work seamlessly. Any suggestions or guidance on how to resolve this issue would be highly appreciated. Thank you!

Answer №1

It seems like the issue might be related to the absence of transitionEnterTimeout and transitionLeaveTimeout, which are responsible for determining the duration during which the *-active classes stay applied.

If these values default to zero, there may not be a visual transition since your CSS transitions are specified on the -active class.

render() {
    return (
        <div className="question-wrapper">
            <ReactCSSTransitionGroup 
                transitionName="fade"
                transitionEnterTimeout={300}
                transitionLeaveTimeout={300}
            >
                {this.showContent()}
            </ReactCSSTransitionGroup>
        </div>
    );
}

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

What is the best way to retrieve data from a jQuery AJAX call when it returns?

function isNewUsername(str){ var result; $.post('/api/isnewusername', {username:str}, function(data) { result = data.result; }, "json"); return result; } I am encounte ...

Retrieving the data from a Material UI Slider control

I'm encountering an issue with retrieving the value property I assigned to a component. event.target.value is returning undefined. How can I successfully access the value of the component? My goal is for handlePlayersChange() to be able to handle dyn ...

"Enhance readability by adjusting the font size on mobile devices and iPhones for an

I'm currently working on a website that needs to maintain a consistent look across all types of devices, including laptops, PCs, iPads, iPhones, and other smartphones. To achieve this, I've implemented fittext.js, a pure JavaScript solution that ...

Handling conditional statements in JSX

Here is an example of my straightforward component: function Messages(props) { return ( <View> <View style={styles.messageWrapper} > <View style={styles.isNotMine}> <View style={s ...

Creating a versatile grid layout with resizable boxes

Currently, I'm working on creating a grid of boxes using CSS and jQuery, but I'm facing an issue with box expansion upon click. The problem arises when the rightmost box is clicked because it doesn't have enough space to expand and ends up m ...

Exploring Next.js: A beginner's attempt at displaying basic JSON data

I'm having trouble updating and displaying the content of my JSON data in my React app. Despite trying various solutions, including adjusting the return value of functions and seeking help on forums, I still cannot get rid of the issue where an empty ...

No output from JavaScript loop when trying to print an array

I've been looking all over the place and haven't been able to find a pure JavaScript solution for my problem that I can implement into my code. The issue involves a script that is meant to display an array of images, but currently it only display ...

Pass JSON data from Laravel to Controller

Recently I started using Laravel 5 and I'm encountering an issue with sending Ajax json data from the view to controller. Here is my routes.php : Route::post('ticket','TicketController@store'); Route::get('ticket', &a ...

Problem with CSS3 Target Selector

As I delve into the world of JS/HTML5/CSS3, I have been immersing myself in code examples from three different authors and combining and modifying them to enhance my learning. You can find my work-in-progress Pen, with references to the original authors, r ...

How can I locate and modify particular element attributes within PHP files in a WordPress template?

Hello everyone, I am relatively new to the world of Wordpress and have recently taken over a project from another developer. The previous developer left behind default placeholders and texts that need to be updated. One specific change I need to make is to ...

Jest is raising a TypeError: Unable to access attributes of an object that is undefined (referencing 'getVideoTracks')

When running my unit tests with Jest, I encountered an error: TypeError: Cannot read properties of undefined (reading 'getVideoTracks') Does anyone have any suggestions on how to properly test the following line using Jest? [videoTrack] = (await ...

I need to create a function that loops through each item in an array and repeats the process for each one

My goal is to create a button for each item in my array fetched from the database. Currently, only the first button functions correctly while the rest do not respond at all. Despite various attempts, I have been unable to resolve this issue. If more code ...

Combining multiple API requests using NodeJS

I'm currently experimenting with SteamAPI to enhance my understanding of NodeJS. My aim is to retrieve game information after making an initial request to obtain the player's profile and storing the game IDs in an array. However, I am facing a ch ...

Efficient method to identify distinct keys within a collection of objects using Typescript

https://i.sstatic.net/qHkff.png I am currently developing an angular application that includes: a group of filters and data records displayed in a table The columns in the table correspond to the filters, where each filter contains unique values from it ...

Prevent key input in Material UI TextField

Is there a way to restrict users from manually inputting values into my Material UI TextField and instead, direct them to use the number stepper? I've attempted a solution without success. import React, { useState } from "react"; import Reac ...

React JS - State values are not persisting and rendering properly upon clicking

Recently, I followed a step-by-step tutorial on creating a todo list using functional components. However, I encountered an issue when attempting to delete or mark items as complete in the list. In both the deleteHandler and completeHandler functions, I tr ...

Understanding the differences between jquery's addClass method and the .css()

After creating a function to set a background on a click event, I encountered an issue. I attempted two different methods, expecting both to be successful. However, only the .css() version worked while the addClass method failed. Why is this happening? fu ...

Efficiently storing and quickly retrieving data from a table for seamless echoing

Details I have created a table using ul and li. Here is the link to view the table: http://jsfiddle.net/8j2qe/1/ Issue Now, how can I efficiently store and display data like the one shown in the image? Each column should only contain one entry. Your r ...

Creating a new item in Angular 2 using user input

Just dipping my toes into Angular2 and attempting to append a new item to the list through input. However, upon clicking submit, instead of text I get [object Object]. Check out the code snippet below: app.component.html <form (submit)="addItem(item) ...

What is the process for incorporating ejs into the source attribute of an image element?

Code Snippet: <img class="card-img-top" alt="..."><%= articles.image %><img> Server Setup: const express = require('express') const app = express() const router = require('./routes/article') app ...