Transition animation when switching between divs in React -

Currently, I am utilizing react-transition-group to assist in managing transitions between different elements. My goal is to create a quiz where each question slides over the previous one once a user answers it. However, I've encountered an issue with my transition causing the divs to stack vertically instead of sliding over like cards. Here is a link to a sandbox example of what I have implemented so far.

Here is the relevant code:

Transition Group Section

 renderQuestion = () => {
    const question = this.questionsToAnswer[this.state.currentQuestionIndex];

    return (
      <div
        style={{
          display: "flex",
          flexDirection: "row"
        }}
      >
        <TransitionGroup className="slide-group">
          <CSSTransition
            classNames="slide"
            timeout={{ enter: 500, exit: 500 }}
            key={`${this.state.currentQuestionIndex}`}
          >
            <div>
              <div
                style={{
                  fontFamily: "Oswald",
                  fontStyle: "normal",
                  fontWeight: 500,
                  fontSize: "28px",
                  letterSpacing: "0.05em",
                  color: "#003E4C",
                  marginBottom: "10px",
                  width: "700px"
                }}
              >
                {question["description"]}
              </div>
              <div>{this.renderRadioQuestion(question["answers"])}</div>
            </div>
          </CSSTransition>
        </TransitionGroup>
      </div>
    );
  };

styles.css Section

/* ANIMATIONS */
.slide-enter {
  transform: translateX(100%);
}
.slide-enter-active {
  transform: translateX(0%);
  transition: transform 500ms ease-in-out;
}
.slide-exit {
  transform: translateX(0%);
}
.slide-exit-active {
  transform: translateX(-100%);
  transition: transform 500ms ease-in-out;
}

/*  not sure how to style this so that i can transition divs nicely*/
.slide-group {
  /* display: flex;
  flex-wrap: nowrap; */
}

Answer №1

To prevent vertical stacking, make sure to also translate the y-axis.

.slide-exit {
  transform: translateY(0%, -100%);
}
.slide-exit-active {
  transform: translateY(-100%, -100%);
  transition: transform 500ms ease-in-out;
}

Check out the CodeSandBox example here: https://codesandbox.io/s/jolly-worker-xht4i?file=/src/styles.css

Answer №2

Special shoutout to 95faf8e76605e973 for guiding me towards the following CSS styles

.slide-exit {
  transform: translate(-100%, 0%);
}
.slide-exit-active {
  transform: translate(-200%, 0%);
  transition: transform 500ms ease-in-out;
}


.slide-group {
  display: flex;/* 
  flex-wrap: nowrap; */
}

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

Errors are encountered when attempting to use `usePathname()` and `useRouter()` functions. `usePathname()` returns null while `useRouter()` causes errors stating "NextRouter not mounted" and "invariant

I'm encountering an issue with implementing active navlinks in NextJS version 13.4.4. I need to access the current URL for this solution, but every attempt ends up failing. My folder structure is organized as follows: .next components Header header ...

Can you explain the distinction between App: React.FunctionComponent and App = (): React.FunctionComponent()?

Currently exploring the depths of typescript. Can someone clarify the distinction between these two code snippets: const App: React.FunctionComponent<CustomProps> = (props: CustomProps) => { return <div>Hello World!</div>; }; and: ...

Stopping arrow key selection in Material UI auto-complete suggestions

I am encountering an issue with my React application that has Material UI Auto Suggest feature. The problem is when I type a name in the auto suggestion box and use the down arrow key to select a suggested name, it immediately changes the input field value ...

TAILWINDCSS: Is there a way to prevent the page from shrinking beyond a certain breakpoint? Take a look at the images provided for visual

Currently, the page can be minimized to a very narrow width as depicted in the image below. https://i.stack.imgur.com/gZqvV.png Is there a way to specify the smallest breakpoint screen size that the page can shrink to this particular width? https://i.sta ...

How can I trigger a reload of an API fetch call when a variable changes in a React JS application

I am developing a custom block for Wordpress using the Gutenberg Editor built on React js. To retrieve data from the Wordpress API, I am using apiFetch(), which operates similarly to fetch(): class PortfolioTagsEdit extends Component { constructor(pro ...

Images that adapt to various sizes while maintaining a consistent visual hierarchy

Hey there, I'm struggling to achieve the same row size of images as shown in the example. However, when I adjust the window size, the larger images become smaller than the columns on the left. This has been a challenge for me and I haven't found ...

Creating a masonry layout with uniform row heights

I am trying to achieve a masonry style layout for these cards in Bootstrap. The current setup has columns with the same height, but I want them to have fluid height and consistent margin spacing like the blue line shown below. I attempted to use .card-colu ...

Energetic flair for Vue animations

I am currently developing a VueJS sidebar component. The objective is to allow the parent to define a width and display a toggle button that smoothly slides the sidebar in and out. Here is an example: <template> <div class="sidebarContainer ...

"Linking a Next.js application with Azure's Application Insights for advanced insights

Trying to include my Next.js (TypeScript) app logs in Azure Application Insights has been a bit challenging. The documentation provided poor guidance, so I decided to follow this solution: https://medium.com/@nirbhayluthra/integrating-azure-application-ins ...

What is causing my nested class to be treated as a sibling rather than a child in HTML code

I have been searching for a clear answer to my query, but haven't found one yet. In my HTML script, I have nested divs structured like this: <ul id="navbar"> <li><a href='#' class='dropdown'>Rules</a> ...

Deploying NextJS: Error in type causes fetch-routing malfunction

Encountering a mysterious and funky NextJS 13.4 Error that has me stumped. Here's a summary of what I've observed: The issue only pops up after running npm run build & npm run start, not during npm run dev The problem occurs both locally and ...

Simply initiating the query within the parent component without displaying any content, then passing all the retrieved data as props

Is there a way to execute a GraphQL query in a parent component without rendering anything and then pass the retrieved data to a child component in React? { ({loading,error,data}) =>{ if(loading ...

What are some ways to address alignment problems that occur with input fields when the file name is lengthy?

When using input type="file", the alignment is not proper when the file name is long with multiple words... https://i.stack.imgur.com/52Yh5.png I would like it so that when the file name is long, it displays like this: From - New_InkDrops_HD_ ...

Can you use TypeScript to define generic React functional components?

I am looking to add annotations to a generic in a React functional component like the following: import React, {useEffect, useState} from "react"; interface PaginatedTableProps{ dataFetcher: (pageNumber: number) => Promise<any>, columnNames: ...

Ways to display success message following JavaScript validation

I've been working on creating a form that displays a success message after JavaScript validation checks are successful. To show the success message, I'm utilizing Bootstrap alert. I split my code into two files - one for common validation functio ...

Updating the color of a radio button in material-ui

import { createMuiTheme, ThemeProvider } from "@material-ui/core"; const theme = createMuiTheme({ palette: { primary: { main: "#5E9C60", }, }, }); const RadioButton = ({ category, handlerForCategory ...

Utilizing React with Typescript to Implement useReducer with Action Interface Featuring Union Type Support

My current challenge involves creating a reducer using the useReducer hook. I have defined an interface named Action which includes a property that can hold either a string or a number: type Actions = 'update_foo' | 'update_bar'; inter ...

Problem with CSS dotted borders appearing as dashed in Chrome when applied to adjacent columns in a table

After testing the code on both Chrome and Firefox browsers, I noticed that they display the border differently. In Chrome, there is a dash in between adjacent cells while in Firefox, there are no dashes rendering. Can anyone suggest a solution to fix thi ...

Adding a div to the preceding div based on matching IDs in AngularJS

Here is a representation of my layout in HTML: <div ng-repeat="message in messages"> <div ng-class="{'messages messages--sent': userId == message.id, 'messages messages--received': userId != me ...

babel-eslint is causing issues preventing me from installing react

Recently I set up a new react App, only to encounter an issue with babel-eslint after adding a name to the react app. [email protected] start C:\Users\Samson Adedayo\Desktop\portfolio react-scripts start Upon investigation, ...