Home > Software design >  Tailwind CSS custom gradient with React state and FastAverageColor
Tailwind CSS custom gradient with React state and FastAverageColor

Time:04-30

I'm trying to add a custom gradient over an image using React state, Tailwind CSS and the FastAverageColor package (https://www.npmjs.com/package/fast-average-color) into my Next JS app. I'm using an useEffect hook for this:

const [avgColor, setAvgColor] = useState("")
useEffect(() => {
        const fac = new FastAverageColor()
        fac.getColorAsync(songData.track.album.images[0].url, { algorithm: 'dominant' }).then(result => {
            setAvgColor(`w-full h-full absolute bg-gradient-to-tr from-[${result.hex}] to-transparent`)
        })
}, [avgColor, songData.track.album.images])

The JSX is presented below:

        <div className="relative w-full h-full">
            <Image priority alt="test" layout='fill' objectFit='cover' src={songData.track.album.images[0].url} />
            {avgColor ? <div className={avgColor}></div> : null}
        </div>

The problem is that my gradient doesn't appear over the image. Do you know maybe why this happens?

CodePudding user response:

It's not possible to do with JIT classes but you can use from-current and set an inline color to set the from color.

So, try this:

setAvgColor(result.hex)

and

<div className="w-full h-full absolute bg-gradient-to-tr from-current to-transparent" style={{color: avgColor}}></div>

basic demo

  • Related