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.