I am currently working on a React app where I’m using Tailwind CSS for styling. I have an array of items (trending), and I’m trying to map through them to create a set of divs with background images. However, I’m facing difficulties with the mapping and setting responsive background images based on the screen size.
{trending.map((value, i) => <div className={`w-[240px] h-[100px] bg-[url(${value.thumbnail.trending?.small})]`}
key={i}>
<svg width="17" height="20" xmlns="http://www.w3.org/2000/svg"><path d="M15.387 0c.202 0 .396.04.581.119.291.115.522.295.694.542.172.247.258.52.258.82v17.038c0 .3-.086.573-.258.82a1.49 1.49 0 0 1-.694.542 1.49 1.49 0 0 1-.581.106c-.423 0-.79-.141-1.098-.423L8.46 13.959l-5.83 5.605c-.317.29-.682.436-1.097.436-.202 0-.396-.04-.581-.119a1.49 1.49 0 0 1-.694-.542A1.402 1.402 0 0 1 0 18.52V1.481c0-.3.086-.573.258-.82A1.49 1.49 0 0 1 .952.119C1.137.039 1.33 0 1.533 0h13.854Z" fill="#5A698F" /></svg> <div className="">
<div><span className="text-primaryText">{value.category}</span><img src="" alt="" /><span></span></div>
</div>
</div>
)}
I tried inline styling but didn’t work.
2
Answers
Tailwind generates a CSS file containing only the classes used in your project. It can’t recognise the dynamically generated class name you’re using so doesn’t include it in the output file.
You are trying to set a background image dynamically based on the
value.thumbnail.trending?.small
property. However, the way you are using thebg-[url(${value.thumbnail.trending?.small})]
class won’t work because Tailwind CSS doesn’t support dynamic values in this way.You may use inline or custom css which includes tailwind property. It provide a way to use its utility classes as CSS variables in inline styles.
I found this issue, it looks like they solved it
Take a look here:
Background image in tailwindcss using dynamic url (React.js)