Search code examples
cssreactjstypescripttailwind-css

Difficulty mapping background images in React app with Tailwind CSS


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.


Solution

  • I found this issue, it looks like they solved it

    Take a look here:

    Background image in tailwindcss using dynamic url (React.js)

    <div style={{ '--image-url': `url(${value.thumbnail.trending.small})` }} 
         className='w-[240px] h-[100px] bg-[image:var(--image-url)]' key={i}>
      ...
    </div>