Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

1K
Views
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?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

I think the best solution is to do what you suggested and use a style attribute. Tailwind CSS doesn't really deal with dynamic data, but rather with class names to add predefined styles to your element. The best you could without using the style attribute is to conditionally add/remove classNames from an element, but that would require you to know the image URL ahead of time, which defeats the purpose of getting it from an API.

I would do:

style={{backgroundImage: `url(${fetchedImgSrc})`}}

Edit: It looks like you can actually use Tailwind to do something similar to the code above as per https://tailwindcss.com/docs/background-image. The code looks like:

<div class="bg-[url('/img/hero-pattern.svg')]">
  <!-- ... -->
</div>
about 4 years ago · Juan Pablo Isaza Report

0

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

<div
  style={{'var(--image-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={{'var(--color)': fetchedColor}} 
  className='text-[color:var(--color)]'>
    <!-- ... -->
</div>
about 4 years ago · Juan Pablo Isaza Report

0

Tailwind Doc: https://tailwindcss.com/docs/background-image#arbitrary-values

You could try something like below

From Doc example (HTML)

<div class="bg-[url('/img/hero-pattern.svg')]">
  <!-- ... -->
</div>

In JSX it would be something like(I might be getting the syntax wrong.)

<div className=`bg-[url('{DYNAMIC_IMG_PATH}')]`>
  <!-- ... -->
</div>
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!