Search code examples
javascriptcssreactjstypescripttailwind-css

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?


Solution

  • 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>