In a Next JS project, the CSS Transition fails to activate when a class is dynamically added

In my Next.js project with Tailwind styling, I encountered an issue when using the globals.css file for more complex non-Tailwind CSS styling on a component.

To better understand the problem, you can view the Code Sandbox here: https://codesandbox.io/p/sandbox/muddy-pine-hx86sf. Essentially, I am trying to achieve this transition when clicking on a list item.

However, in both the Sandbox and my local Next.js development environment, the transition is being skipped and the new background color is applied immediately without playing out the transition.

I'm uncertain if I'm misunderstanding how CSS transitions work or if this issue is related to Next.js or my lack of understanding in dynamically applying CSS to elements.

  1. I attempted manually applying the class that changes the background position active-location-item using Firefox DevTools, which made the transition work.
  2. I tried different CSS selectors but still faced the same issue of no transition occurring.
  3. I confirmed in DevTools that the class is indeed applied when the item is clicked.

Any assistance on this matter would be greatly appreciated!

Answer №1

The issue arises from the fact that a new component is being returned within the Modal. With each state change, the const LocationView gets initialized again. This leads to React treating LocationView as a fresh component since it's not the same reference on re-rendering, causing it to be remounted and resulting in no transitions.

To resolve this, you should directly return the JSX:

const { useState } = React;

const Modal = () => {
  const [activeLocation, setActiveLocation] = useState("");

  const handleLocationClick = () => {
    setActiveLocation("Example");
  };

  return (
    <div className="flex flex-col w-[600px]">
      <div className="flex flex-col text-hsr-dark font-medium grow">
        <ul className="list-disc list-inside">
          <li
            onClick={handleLocationClick}
            className={`${
              activeLocation === "Example" ? "active-location-item" : ""
            } location-item cursor-pointer text-2xl p-10 outline outline-2 outline-transparent  mb-1`}
          >
            Example
          </li>
        </ul>
      </div>
    </div>
  );
};

ReactDOM.createRoot(document.getElementById('app')).render(<Modal/>);

tailwind.config = {
  theme: {
    extend: {
      colors: {
        "hsr-dark": "#404040",
        "hsr-grey": "#BFBFBF",
      },
    },
  },
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js" integrity="sha512-8Q6Y9XnTbOE+JNvjBQwJ2H8S+UV4uA6hiRykhdtIyDYZ2TprdNmWOUaKdGzOhyr4dCyk287OejbPvwl7lrfqrQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js" integrity="sha512-MOCpqoRoisCTwJ8vQQiciZv0qcpROCidek3GTFS6KTk2+y7munJIlKCVkFCYY+p3ErYFXCjmFjnfTTRSC1OHWQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdn.tailwindcss.com/3.3.2"></script>

<div id="app"></div>

<style type="text/tailwindcss">
:root {
  --foreground-rgb: 0, 0, 0;
  --background-start-rgb: 214, 219, 220;
  --background-end-rgb: 255, 255, 255;
}

.location-item {
  background-image: linear-gradient(
    to right,
    theme("colors.hsr-dark") 50%,
    theme("colors.hsr-grey") 50%
  );
  background-size: 200% 100%;
  background-position: right bottom;
  transition: all 0.75s;
}

.active-location-item {
  background-position: left bottom;
}
</style>

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

Module 'has-flag' not located

Encountering an error when running "npm run build" on the server. It works fine on my local machine, but I'm getting a 500 response on the server. Node version: 8.0 Npm version: 5.0.3 Error: Cannot find module 'has-flag' at F ...

Alert displayed on console during transition from MaterialUI lab

Whenever I try to run my MUI application, an error pops up in the console It seems you may have forgotten to include the ref parameter in your forwardRef render function. import { LoadingButton } from "@mui/lab"; const LoadData = ({loading,sig ...

Is it possible to copy text from an iframe to the clipboard?

I have encountered an issue in my React app where I am trying to copy text from a card when the user clicks on it. The app displays multiple cards by looping through an array, so there can be any number of cards (n). The problem arises because the React a ...

"Varying hues on various displays: Exploring RGB values and CSS for video color

Recently, I designed a webpage with a background-color of #f4afac. The video embedded in this page also features the same background color throughout, creating a seamless blend with no visible edges. On one screen, the colors appear perfectly consistent. ...

Ways to resolve the error "Uncaught TypeError: data.map is not a function"

Currently developing an app using reactJS and encountering the following error in the console when using the map function: TypeError: data.map is not a function. Despite successful API data calling as confirmed by console.log, the error persists when tryin ...

Parsing a string into a React component: A step-by-step guide

If I have a variable const text = "I love $FB", and I want to achieve the following: <p>I love <a href="/symbol/FB">$FB</a></p> using <RenderContent content={text}> I know I can use regular expressions to extract the symbol, ...

Is there a way to retrieve the API response from Antd's upload action once the upload has been completed?

Currently, I am utilizing Antd's Upload component for my image uploads to Cloudinary. Upon successful upload, the response provides details about the file, including the file URL on the server. Any suggestions on how I can retrieve this file URL from ...

Creating a multiline centered navigation bar item using Bootstrap 4

My navigation bar is functioning properly with single-line items, but encounters alignment issues when dealing with multi-line items: <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav ml-auto"> ...

Asynchronous data fetching adding two entries to an array

I've been experimenting with making API calls for Rick & Morty using fetch and async arrow functions, but I've run into an issue where the elements are being added to my array twice. I've tried calling the function both with and without useE ...

A single image with dual clickable areas managed by an interactive image map

Is there a way to attach two href links to one image using CSS? I want it to function like an old school image map, but purely with CSS. Is this something that can be done? The current HTML code looks like the example below. However, I need the image to h ...

When using HLS with Media Source Extensions on mobile devices, the <video> element with the muted and autoplay attributes may freeze on the first frame

I recently added a background video to our website using mux.com. The video is set to autoplay with HLS, but Chrome requires Media Source Extensions for playback. To ensure the HTML5 video auto plays, I included the necessary mute parameters as well. How ...

Tips for making inline elements match the line height

Consider this block element : <div style="background-color: gray; line-height: 30px;"> Some text and a <a style="background-color: yellow;">link<\a> <\div> Why is it that the yellow color does not extend the full hei ...

Resizing a floated div causes the image to break out

My webpage has a container div with two floated left divs inside, positioned side by side. The right div contains a YouTube video and an image. However, when I resize the page, the video and picture flow out of the containing floated div instead of dropp ...

Any suggestions on troubleshooting the error when trying to create a React app?

When I ran the command npx create-react-app projectName, I encountered this error message and the app was not created. Can anyone explain why this error occurred? npx: installed 99 in 8.22s I received an error related to ES Module loading while trying to ...

Subclass declaration with an assignment - React.Component

I recently started going through a React tutorial on Egghead and came across an interesting class declaration in one of the lessons: class StopWatch extends React.Component { state = {lapse: 0, running: false} render() { const ...

What steps can I take to prevent the odd gaps from appearing in my horizontal flexbox gallery?

Take a look at this code: .gallery { display: flex; overflow-x: auto; resize: both; background-color: rgb(200, 200, 200); padding: 10px; height: 200px; } .item { display: flex; flex: 0 0 auto; max-width: 100%; } .item img { max-w ...

Tapping the image will redirect you to the corresponding component

My React Routes Challenge I've run into a roadblock while trying to implement react routes in my project. Greetings, everyone! This is my first time seeking help here, as I have previously posted about this issue on Codecademy. Below is the summary o ...

Troubleshooting Problems with Fancybox Scaling on Small Landscape-Oriented Mobile Devices

Issue Description: In my responsive web design, I am utilizing Fancybox v2.1.5. The problem arises when smaller mobile devices with a more rectangular shape than square are used. In portrait orientation, when invoking Fancybox, it expands to the width of ...

Invisible style date input value on iPhone mobile devices

My goal is to enhance the appearance of an HTML5 input with a custom icon, using a font pack. Although I mention FontAwesome in this example, in reality, I'm utilizing a different custom font pack. On my mobile device (iPhone X), I can see the calend ...

`Incompatibility issue between HTML, CSS and Chrome browser`

There seems to be an issue with the left menu not displaying properly on the website in Google Chrome. Interestingly, it appears correctly aligned at the bottom of the menu in Firefox (blue), but in Chrome, it is positioned in the middle. Despite the co ...