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

Adding flair to the selected element in the HTML nav bar

I was attempting to customize the appearance of the active item within an HTML navigation bar, which corresponds to the a element. To test this out, I used the example from Here is my modified code, where I introduced a new class "active" and applied the ...

What is the best way to insert a React component or raw HTML into another React component?

Dealing with raw HTML markup returned from an AJAX call can be tricky in React. I've tried using dangerouslySetInnerHTML, but React just throws errors when I do. It's like trying to navigate through a maze. After some trial and error, I decided ...

Modifying Material-UI to Remove Shadows and Customize Components

I am looking to implement the <AppBar> component from Material UI, but I want to remove the shadows it generates. After some research, I found a solution that involves using createMuiTheme and MuiThemeProvider to set the default shadow as: const th ...

Uninitialized process.env variables in Nextjs

My environment variable is showing as undefined. Even though I defined it in my .env file at the root directory, when I console log process.env, the variable can't be found. .env.local file privateKey="444455....." scripts/hardhat.config.j ...

The absence of dependencies in React's useEffect

I keep receiving a warning about missing dependencies in my useEffect, but I am hesitant to add them because it will cause the page to refresh whenever I alter the input values of these dependency fields. Currently, I have two state variables for my start ...

Is it possible to transition an existing T3 Stack (TypeScript, Tailwind, trpc) application from a 'page router' setup to an 'app router' setup?

Lately, I've been immersed in a project that was originally set up using the t3 stack with Next.js 'page router'. However, I have decided that I want to switch to using the 'app router' in this project. The current version of Next. ...

Attempting to create a cookie in getServerSideProps with next.js

Trying to set a cookie in getServerSideProps has been a bit tricky for me. Even though I can successfully read it using `req.headers.cookie`, setting it doesn't seem to work. I've tried different methods, like using libraries such as cookies-next ...

Refresh PHP Calculator Display Once Results are Shown

Currently working on a basic calculator project coded in HTML, CSS, JS, and PHP. Here is a glimpse of it: The user input retrieval is handled by JS, while the actual calculations and result display are taken care of by PHP. I am striving to clear out the ...

Unique arrangement of hexagons in a honeycomb layout with precise centering

Currently, I am having trouble creating hexagonal blocks with content in a specific layout. My goal is to have four blocks starting with one at the top, followed by a row of two, and finishing with a row of one as shown in the image below. Unfortunately, a ...

Modifying Row Color in Bootstrap 3: A Step-by-Step Guide

I'm trying to customize the background color of alternating rows in a Bootstrap 3 grid. I attempted to use CSS and add it to the class within the div, but unfortunately, the color isn't changing as expected. Below is the CSS code I used: .row-b ...

Having trouble incorporating a title in the header section

I encountered an issue while attempting to include the Fragment, title, and Head. When these are added, an error occurs but when removed, the page displays correctly. I have searched for a solution to this problem but couldn't find anything. import ...

React Virtualized - Blank screen issue occurring because of continuous scrolling through a large list of ITSM items

I am currently working on a lengthy list of items and utilizing the react-virtualized library for this purpose. However, I have encountered an issue that needs addressing. https://i.stack.imgur.com/ROdjp.gif Upon attempting to scroll down for 2 seconds, ...

Acquire the value of ant-design Select dropdown upon hover

How can we detect the selected option in an ant-design dropdown when it is hovered? <Select defaultValue="lucy" style={{ width: 120 }} onChange={handleChange}> <Option value="jack">Jack</Option> <Option value=& ...

What causes the width of unrelated cells to change when the contents of colspan'd cells expand in IE7?

Before we delve into the details, I invite you to take a look at this fiddle using IE7. It's quite intricate and not something I want to repeat here. The main issue is that clicking on the red block should display additional information. The top row ...

Transferring information from ReactJs via the fetch API to a nodeJs server

I've encountered an issue where I am sending JSON data from my React application using the Fetch API, but on the server side, the req.body is showing up as empty. I'm not sure what the problem could be. Here is a snippet of my React code: impor ...

Make sure to attach the zipped secure connect file when deploying your Next.js app on Amplify for added

Connecting to the Datastax Astra-DB Cassandra Database in node.js used to be done with a driver named 'cassandra-driver'. This driver required a connection secret key file called secure-connect-{DB-Name}.zip. The syntax looked like this: const cl ...

Encountering a "Module Not Found" error when trying to add a background image using Tailwind

I've been trying to set a background image for a component in my next.js application, based on the structure of their sample blog project. However, when I try to preview the page locally, I encounter a 404 error while attempting to locate the image. ...

The issue with SetValue in mui Select and React hook form is causing problems

When the page loads, I would like to set the value initially. If needed, the value should be able to update as it is a multiSelect element. const options= [ { label: 'Apple', value: 'Apple' }, { label: 'Grape', value: &apo ...

Encountered an error when attempting to load the external module @babel/register during the

My React project runs smoothly on my VMware, but when I cloned the same app and executed the gulp command, I encountered an error during compilation: MacBook-Pro:Frontend1.0 apurvgandhwani$ gulp [18:42:31] Failed to load external module @babel/register ...

Struggling to display nested data using ReactJS and Material-UI?

Struggling to implement Tabs and display data from a JSON file in Reactjs with an older version of material-ui. Despite following suggestions on StackOverflow to correct the nested map in JSX, the data is still not appearing under each tab. For reference ...