Search code examples
reactjstailwind-cssbackground-image

Custom Tailwind background image works for a specific image, not for the others


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


Solution

  • 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:

    If you use string interpolation or concatenate partial class names together, Tailwind will not find them and therefore will not generate the corresponding CSS

    You can use an inline style instead.

    <div className={yourClassName}
         style={{backgroundImage: "url('../public/" + symbol + "')"}}>
        { /* children */ }
    </div>