Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Tailwind CSS custom gradient with React state and FastAverageColor

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading