Home > Enterprise >  How to put an image variable as a background using tailwind in React?
How to put an image variable as a background using tailwind in React?

Time:08-13

Hey i am learning React and i am creating a React application where in one of my components i am importing one of my images from my imagefolder.

import Image from '../images/image.jpg';

I would like to use this image as a background by using a tailwind className

export const Gallery = () => {

    return (
        <div className="bg-[url('{Image}')]"></div>
    )
}

i tried it this way but the image isnt rendering and i get nothing back.

Did i do something wrong here? Thanks in advance!!

CodePudding user response:

Instead of importing the image, simply reference the image path:

<div className="bg-[url('../images/image.jpg')]"></div>

CodePudding user response:

Imho, The best way to do this will be to extend theme in tailwind config.

module.exports = {
  theme: {
    extend: {
      backgroundImage: {
        'hero-pattern': "url('/img/hero-pattern.svg')",
        'footer-texture': "url('/img/footer-texture.png')",
      }
    }
  }

tailwind docs

  • Related