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?
CodePudding user response:
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 >
<!-- ... -->
</div>
CodePudding user response:
Tailwind Doc: https://tailwindcss.com/docs/background-image#arbitrary-values
You could try something like below
From Doc example (HTML)
<div >
<!-- ... -->
</div>
In JSX it would be something like(I might be getting the syntax wrong.)
<div className=`bg-[url('{DYNAMIC_IMG_PATH}')]`>
<!-- ... -->
</div>
