1

I'm using Tailwind in my React Project. I want to add a background image in a div but it shows the following error:

Module not found: Error: Can't resolve '../../icons/blog-hero-1.png' in 'C:\Users\DELL\frontend-development\aidhumanity-practice-2\src'

I'm adding tailwind class

bg-[url('../../icons/blog-hero-1.png')]

for adding background image and url is relative to the current file and also it's working when added normal image through:

import Hero from "../../icons/blog-hero-1.png"
<div>
  <img src={Hero} className="h-full rounded-3xl"></img>
</div>

Can anyone guide how to give the correct url? Note: I've added a codesandbox example here as well for better demonstration in which I've tried to import background image in "Homepage.js" but it's not working. https://codesandbox.io/s/background-image-wl9104?file=/src/components/Homepage.js

Fuaad
  • 197
  • 15
  • can you please let us know which version of tailwind css you are using? I believe the feature of using background image as Arbitrary values is introduced in the v3.2.6. – Sam Phillemon Feb 12 '23 at 09:03
  • @Sam My package.josn indicates "tailwindcss": "^3.2.4"... Can you please confirm whether this version of tailwind supports this feature or not? – Fuaad Feb 12 '23 at 13:28
  • it working for 3.2.4. I have checked. Well you might need to rebuild the tailwind css or restart the server once to see the images. I have created a sample for you in tailwind playground: https://play.tailwindcss.com/e4az4dl6ok . Its version is 3.2.6 but the implementation is same. I have noticed that I needed to add the 'whitespace-pre' in my tailwind class. Hope it helps. – Sam Phillemon Feb 12 '23 at 16:42
  • have you tried using unsplash inside url() like @SamPhillemon tailwind playground example? is it work? just to make sure your tailwind version and setup is right – Ashar Setiawan Feb 16 '23 at 11:13

1 Answers1

0

Well you can achieve the same result with the below approach as well:

In your tailwind.config.js file:

module.exports = {
  theme: {
    extend: {
      backgroundImage: {
        'hero': "url('../../icons/blog-hero-1.png')"
      }
    },
  },
  plugins: [],
}

You can simply mention bg-hero in you class to implement.

Sam Phillemon
  • 202
  • 3
  • 10
  • Tried this but not working. – Fuaad Feb 12 '23 at 13:30
  • Well Its working on my end. I have created a sample for the above approach: https://play.tailwindcss.com/dp4DPVlA5w . Please have a look and see if you are missing anything. Else please share your code online editor or something to give you better answer. – Sam Phillemon Feb 12 '23 at 16:44
  • ! here you can see what I'm trying to do...https://codesandbox.io/s/tailwind-css-and-react-forked-wl9104?file=/src/components/Homepage.js... I've added a background image in Homepage.js which isn't showing. please have a look. – Fuaad Feb 16 '23 at 04:51