I use React, NextJS and Tailwind.
I want to use some images as background for some cards elements.
I first store the images names in an array.
const symbols = ['boat_2.png', 'boat.png', 'tortue.jpg', 'surf.jpg'];
Then I map the array and pass the name in the child elements.
{symbols.map((symbol, index) => (
<ChildElement
key = {index}
symbol = {symbol}
/>
))}
In the child element I use the name to fit the the Tailwind syntax : bg-[url(‘imagepath’)]
var bgImg = "bg-[url('../public/" + symbol + "')]"
console.log(bgImg)
The path is correctly displayed in the console.
Finally I use the bgImg variable in the className for my div element.
return (
<div
className={`${bgImg} bg-cover bg-center bg-no-repeat aspect-[5/7] border-2 rounded-xl border-black`}
>
</div>
)
The problem is only the boat.png is working.
All others images are not displayed.
I tried to access my images (through localhost:3000/surf.jpg for exemple) and it works.
I restart my browser, visual studio. Nothing worked.
I though it could be the image format. So I copied my boat.png in the folder and renamed it boat_2.png.
boat.png still works but boat_2.png doesnt.
I tried to make custom backgroundImage in the tailwind.config.ts like
backgroundImage: {
'surf': "url('../public/surf.jpg')",
},
This last method (using className = bg-surf) worked. But I want to understand why the first method works only for le boat.png image.
Since it’s a one-time use background images I dont want to specify them in the tailwind.config.ts and would like to fix the first method. (Maybe I’m wrong and should use this way)
Thanks for any advices
3
Answers
Although using the
style
property seems to work fine I stick with the tailwind className.Based on the documentation I ended up doing this :
bg-* declared on imgVariants are from the tailwind.config.ts I used the tailwind.config.ts to avoid using relative pathname.
This is most likely postcss thats not got the classes included so they are being striped out when your app builds. I think you can try whitelisting those, or by whitelisting a regex of bg-*, which might not work.
But if all else fails you can just use css directly in the div like so:
Then style the rest of it using tailwind.
Tailwind cannot handle dynamically concatenated strings to form a single class name, as the full class name does not appear in the source code.
See the documentation:
You can use an inline style instead.