Home > front end >  How to use a dynamic background image URL with Tailwind CSS and React
How to use a dynamic background image URL with Tailwind CSS and React

Time:11-14

In React, I'm unable to use a URL string in my Tailwind background image class:

1: Not working, getting error "can't resolve ${link}"

const link = "https://cdn.test.net/test.jpg";

<div className={`px-4 py-1 h-[22rem] lg:h-[28vw] bg-cover bg-center bg-[url('${link}')]`}></div

2: Working, but I need to use a variable inside my bg- class.

const link = "bg-[url('https://cdn.test.net/test.jpg')]";

<div className={`px-4 py-1 h-[22rem] lg:h-[28vw] bg-cover bg-center ${link}`}></div>

I still need to be able to use ${link} inside bg-[url('${link}')].

CodePudding user response:

Here is how it looks for me

The given example should be working fine. Working fine for me.

CodePudding user response:

The CSS file generated by Tailwind will only include classes that it recognizes when it scans your code, which means that dynamically generated classes (e.g. bg-[url('${link}')]) will not be included.

If you only have a few different background images, you could add them to your tailwind.config.js and switch between them:

module.exports = {
  theme: {
    extend: {
      backgroundImage: {
        'first': "url('/img/first.jpg')",
        'second': "url('/img/second.jpg')",
      }
    }
  }
}
<div className={`bg-cover bg-center ${useFirst ? 'bg-first' : 'bg-second'}`}></div>

This would work, as long as you use the full utility class name, e.g. bg-first, in the code for Tailwind to find and include in the generated CSS.

If you need to reference completely arbitrary URL values, you can always use a style attribute instead of Tailwind classes. For example:

<div className="bg-cover bg-center" style={{backgroundImage: `url('${link}')`}}></div>
  • Related