Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Background image in tailwindcss using dynamic url (React.js)

I have an image url fetched from an API and I want to display it as a background image. Is there any way I can implement this with tailwindcss or should I use styles attribute?

like image 751
Tenshi Munasinghe Avatar asked Aug 30 '25 15:08

Tenshi Munasinghe


1 Answers

I think I have found a solution other than simply using a style attribute.

<div
  style={{'--image-url': `url(${fetchedUrl})`}} 
  className='bg-[image:var(--image-url)]'>
    <!-- ... -->
</div>

This works perfectly fine.

Although it looks a bit tedious, it can be used to enable the background image on hover, focus, etc. In which the style attribute is incapable of.

className='hover:bg-[image:var(--image-url)] focus:bg-[image:var(--image-url)] ...'

This application of custom properties can be used for implementing dynamic values with tailwind like colors fetched from an API.

<div
  style={{'--color': fetchedColor}} 
  className='text-[color:var(--color)]'>
    <!-- ... -->
</div>
like image 181
Tenshi Munasinghe Avatar answered Sep 13 '25 07:09

Tenshi Munasinghe