2

Say I have a React functional component with some simple state:

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

export default function Basket() {
    const [itemCount, setItemCount] = useState<number>(0)

    return (
        <div>
            <Count count={itemCount} />
            <button onClick={() => setItemCount(itemCount + 1)}>
              Add One
            </button>
        </div>
    )
}

function Count({count}: {count: number}) {
    const classes = useStyles()

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

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

I want the Count component to apply a property whenever the count changes and then remove it again; say, turn on backgroundColor: yellow for 2 seconds and then gradually fade it over 1 second. What's the simplest way to achieve this?

Note that presumably this could be either triggered by a state change on the parent or by a re-rendering of the child. Alternatively, I could add the key property to <Count/> to force a re-mount of the child:

<Count 
  key={itemCount} 
  count={itemCount} 
/>

Any of those would be acceptable; I'm looking for the simplest, cleanest solution, hopefully one that doesn't require additional state and is compatible with Material-UI styling APIs.

Sasgorilla
  • 2,403
  • 2
  • 29
  • 56

1 Answers1

1

Just an idea.

const Component = () => {
  useEffect(() => {
    // will trigger on component mount

    return () => {
      // will trigger on component umount
    }
  }, [])
}

...

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

You can use useEffect along with useRef containing a reference to the element or directly getting it with document.getElementById and then update the transition class that way in component mount/unmount. Not sure if it'll work, I haven't tested it myself.