What is the best way to implement a CSS transition in React when the state changes, the component remounts, or it re-rend

Imagine having a React functional component with some basic state:

import React, { useState } from 'react'
import { makeStyles } from "@material-ui/core"

export default function Cart() {
    const [itemNumber, setItemNumber] = useState<number>(0)

    return (
        <div>
            <Amount number={itemNumber} />
            <button onClick={() => setItemNumber(itemNumber + 1)}>
              Add One
            </button>
        </div>
    )
}

function Amount({number}: {number: number}) {
    const classes = useStyles()

    return (
        <div className={classes.amount}>
            {number}
        </div>
    )
}

const useStyles = makeStyles({
    amount: {
        backgroundColor: "yellow",
        transition: "backgroundColor 2s ease"  
    }
}

The goal is to make the Amount component apply a property whenever the number changes and then remove it again; for example, turning on backgroundColor: yellow for 2 seconds and then gradually fading it out over 1 second. What's a straightforward way to achieve this effect?

This could be triggered by either a state change in the parent component or by a re-render of the child component. Another approach would involve adding the key attribute to <Amount/> to force a re-mount of the child component:

<Amount 
  key={itemNumber} 
  number={itemNumber} 
/>

Any of these methods are acceptable; seeking the simplest, cleanest solution that doesn't necessitate additional state management and works seamlessly with Material-UI styling APIs.

Answer №1

Here's an interesting concept to consider.

const Component = () => {
  useEffect(() => {
    // This code will execute when the component mounts

    return () => {
      // This code will execute when the component unmounts
    }
  }, [])
}

...

document.getElementById('transition').classList.add('example')

You can utilize useEffect in combination with useRef to hold a reference to the element, or obtain it directly using document.getElementById. You can then modify the transition class during component mount/unmount this way. It's worth testing out to see if it functions as intended.

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

Which authentication details should be utilized for deploying a React application on AWS?

After developing an app that leverages amplify for deployment and dynamodb for data retrieval, I am pondering the idea of using separate credentials solely for deployment purposes. The current set of credentials seems to be working fine for me, but is it r ...

The content contained within the .each loop within the click event is only executed a single time

While working on coding a menu opening animation, I encountered an issue today. Upon clicking the menu button, the menu opens and the elements inside receive an added class (resulting in a fade-in effect). Clicking the menu button again should close the ...

When using npm bootstrap in a React project, the JavaScript features may not function properly

I am currently working on a React project and I needed to add a navbar. To achieve this, I installed Bootstrap using the following command: npm install bootstrap After installation, I imported Bootstrap into my index.js file like so: import 'bootstra ...

Is it possible to override Material UI styles with css/scss?

Currently, I am using SCSS because it integrates well with NextJS. I find the SCSS module system easy to work with and would like to continue using it with Material-UI. However, Material-UI uses JSS which involves a lot of boilerplate code. I prefer not to ...

Difficulty encountered in displaying HTML within a React component

Struggling to display HTML in my React code, whenever I click 'signup' after starting the page, it shows the 'login' view instead. Could there be an issue with how I'm linking everything together? App.js class App extends Compon ...

Utilize Material UI AutoComplete in React to showcase a variety of choices in a list and capture various selections in the form state, including multiple values

I'm looking to implement Autocomplete in a way that it saves a specific property of an object in the form state and displays a different property in the autocomplete options list. For instance, if we have the following option list: [ { gender_name ...

Rendering React component within a production build of Angular 7

I've been in the process of gradually moving an Angular app to React. After exploring options like single-spa and nx, I found that they weren't suitable due to the messy script-injected nature of the existing app. So, I decided to go for a semi-m ...

Creating a dynamic form that efficiently captures user information and automatically redirects to the appropriate web page

Sorry for the unusual question, but it was the best way I could think of asking. I have come across websites with fill-in-the-blank lines where you can input your desired information and then get redirected to another page. For example: "What are you sea ...

Is there a way to restrict the number of words displayed in React? Check out this code snippet: `<ProductImg imgtext={products.description}/>`

imgAlt={product.name} Note: Consider the product name as: HD Single Sided Cantilever Rack. In this case, only HD Single Sided... should be displayed Please find the code snippet below <ProductImg imgtext={products.description}/> ...

Having trouble with JavaScript not working when clicking an image and toggling a div?

Why isn't the onclick image and toggle div functionality working with JavaScript? I made the change from: <input type="button" id="Showdiv1" name="Showdiv1" value="Show Div 1" onclick="showDiv('div1')" /> to: <img src="https://d ...

Invoking a function in a React component from another component

I am trying to implement a page with the structure shown below: const Upload = (props) => { return ( <BaseLayout> <ToolbarSelection /> <Box> <FileDropArea /> </ ...

Material-ui allows for easy customization of text with a maximum of 2 lines and an ellipsis

When developing a reactjs app, I decided to use Material-ui for the design elements. One issue I encountered was trying to ensure that text in a card displayed exactly two lines. My current implementation works fine for short text that fits within one or ...

What is the method to initialize a Stripe promise without using a React component?

I have encountered an issue while implementing a Stripe promise in my React app. The documentation suggests loading the promise outside of the component to prevent unnecessary recreations of the `Stripe` object: import {Elements} from '@stripe/react-s ...

Tips for enlarging the stepper in MUI

Looking to customize the stepper component by increasing its size and adding a horizontal line before the initial step content. I've tried adjusting width and height properties in my code, but it hasn't worked so far. Any suggestions on how to ac ...

Creating a responsive layout with Bootstrap using fluid rows and columns of varying heights

Using dynamic creation, I am tasked with generating a set of boxes each with slightly varying heights and ensuring that 2, 3, or 4 of them (based on screen size) appear on the same row. Here is an example of my attempt using Bootstrap: <div class="cont ...

Using a template literal as a prop is causing rendering issues

I have a functional component const CustomParagraph = forwardRef((ref: any) => { return ( <div> <p dangerouslySetInnerHTML={{ __html: props.text }}></p> </div> ); }); Whenever I use this component, I am unable ...

When hovering over the main menu, the submenu appears hidden behind it

I am struggling with setting up a dropdown submenu on my website that uses a responsive Joomla template. The submenu always appears behind the main menu and slider, despite trying z-index and relative positioning. Can anyone help me figure out what I' ...

Left-hand navigation panel that complements entire screen

Web Design .sidenav { height: 100%; position: relative; overflow-y: scroll; background: #000000; width: 15%; } Ensuring the menu covers the full screen correctly by setting its height to 100% is effective, but it may appear awkward wh ...

Utilizing the bold attribute in Material-UI (React) for enhanced styling

I have a Typography component from Material-UI (MUI) and I am looking to implement a bold option using a boolean type. Here is my Typography component: import React, { FC } from 'react'; import Typo from '@material-ui/core/Typ ...

Could it be a path problem if you're directed to the incorrect slug without any errors popping up?

I have two slugs. I'm encountering an issue where I am trying to access the second slug [product] but instead, it keeps redirecting me to the first one [slug]. The slugs are stored in separate folders and there aren't any error messages being dis ...