I've just recently picked up React and Tailwind for a project, and I am still very much a beginner. I wanted to make an element have a background image as a custom class variable, something like this:
<div className="bg-[url(`https://example.com/${variable}.png`)]"></div>
But as Tailwind purges classes, would this somehow be possible? I hope I'm not missing anything, but it doesn't seem doable to me right now
Tailwind has a feature called "safelisting" which may provide you with the functionality you need – see here in the docs.
That said:
1 - There's nothing wrong with using both className and style props on the same element – you can have e.g. <div className="w-full" style={`background: url(https://example.com/${variable}.png`}>
2 – Depending on what flavor of React you are using, your might be better off using a component like Next.js's Image to optimize your images instead of setting background via CSS. Below is how I do it:
import Image from "next/image";
export default function MyBackground(props) {
return (
<div
className="z-0 absolute inset-0 w-full h-full flex justify-center items-center"
>
<Image
placeholder="blur"
alt={props.alt}
src={props.src}
className="h-full w-full object-cover"
/>
</div>
);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With