90

I'm trying to access a static image to use within an inline backgroundImage property within React.

i am working with reactjs and next.js then i faced an issue with adding images with next.js but fixed this by using image loader called : Next.js + Images,

now i could add images normally with normal html img tag

Example: <img src={ img } /> this works.

but when i tried to add css background images as the following:

const team = (props) => {
const img = require("../../assets/images/security-team.jpg");
const styling = {
    backgroundImage: `url('${img}')`,
    width:"100%",
    height:"100%"
}
console.log(img);
return (
    <div className="team" style={styling}>

    </div>
);

}

here was the console.log results :

/_next/static/images/security-team-449919af8999ae47eaf307dca4dda8e1.jpg

the image doesn't appear and no errors happened then, i tried to type in the browser website-url + the console.log results the image appeared !

2
  • 4
    Add ".src" to line 4 of your code: backgroundImage: url('${img.src}'), Commented Mar 21, 2022 at 5:48
  • 1
    what does ".src" do here? Commented Jan 20, 2023 at 8:58

22 Answers 22

141

First import the image file

import bg from '../../assets/images/security-team.jpg'

then apply inline style

style={{
      backgroundImage: `url(${bg.src})`,
      width: '100%',
      height: '100%',
    }}
Sign up to request clarification or add additional context in comments.

6 Comments

.src is the main thing
@M.lslam : backtick helped me
what does ".src" do here?
When you import the image as bg then it return an object. This object will provide you the src property that is the path of the image. You can use console log to see the object on console.
Does Nextjs optimise the image like it does with <Image/> if you import it this way?
|
55

With [email protected] I had my image in the public folder and then in the style file I used the following and it worked.

background-image: url('/image.svg');

1 Comment

the problem with this is anything in public has headers telling browsers not to cache it, so your client will end up fetching the image on every page load
32

All the solutions here don't allow the main benefits of NextJs custom <Image> component which serves optimized, responsive images by default and has immense benefits. When I can, I use z-index to "fake" a css background image.

However, this method does have the limitation of not having repeatable options like a CSS background would.

Note that this example uses Tailwind CSS.

<div className="h-screen">
    <div className="absolute -z-10">
        <Image
            src="/some.jpeg"
            layout="fill"
            objectFit="cover"
            quality={100}
        />
    </div>
    <div> Some overlay things go in here </div>
</div>

3 Comments

This is nice, using the <Image> component is a big plus
True. but the background image has properties that you cannot use with image developer.mozilla.org/en-US/docs/Web/CSS/background-image
I needed to add inset-0 to the absolute wrapper for it to show up for me. <div className="absolute inset-0 -z-10">
22

css file in styles/home.scss

Image file in public/bg-img.png

.content_bg {
    margin: 50px 0;
    background-image: url('../public/bg-img.png');
    height: 500px;
    background-size: cover;
    background-repeat: no-repeat;
}

3 Comments

this solution works, it just should be mentioned that those images will be added to the bundle during build, so better not to place them in /public folder to avoid confiusion
👍This answer explains nicely with image path. most of the time that is the issue. Thanks
this works as of date . the '../' way of addressing the path did the trick. thanks
15

The package next-images works for me.

First :

yarn add next-images

Then, in a next.config.js file :

const withImages = require('next-images')
module.exports = withImages()

Then you can do :

<div
  style={{
    backgroundImage: "url(" + `${require("./path-to-the-image")}` + ")",
    width: "100%",
    height:[HEIGHT OF THE IMAGE],
    backgroundRepeat: "no-repeat",
    backgroundSize: "cover"
  }}
>XXX</div>

For more info on next-images : https://github.com/twopluszero/next-images

3 Comments

Can you mention the way to solve the problem and explain the modifications you made to the code?
I've edited my answer to show the entire process. It's quite straight-forward.
That's right, thanks for your cooperation It is clear now
10

As nextjs documentation says (https://nextjs.org/docs/basic-features/static-file-serving):

Next.js can serve static files, like images, under a folder called public in the root directory.

Files inside public can then be referenced by your code starting from the base URL (/).

So the right way to reference our images from the public folder:

CSS example:

background-image: url('/your-image.jpg');

JSX example:

import Image from 'next/image'
<Image src="/your-image.jpg" alt="Image description" width="64" height="64" />

1 Comment

Sometimes devs need to put the images as background for divs, can we leverage next/image in this use-case?
6

when i used JSX styles then added position absolute property it worked just fine.

Like this:

 <style JSX>{`
    .team {
        width:100%;
        height:100%;
        position:absolute;
        background: url('`+img+`') no-repeat;
    }
`}</style>

Comments

4

all what you have to do is to change url

from background-image: url('/public/images/my-img.jpg');

to background-image: url('/static/images/my-img.jpg');

Comments

4

I'm using Next.js v12.0.10, and it fails to load css background image when I try something like:

<div style={{ backgroundImage: "url('/public/a.jpg')"}}>
</div>

but when I omit the /public in the image url, everything works:

<div style={{ backgroundImage: "url: '/a.jpg')"}}>
</div>

Just like Ivan says above:

Files inside public can then be referenced by your code starting from the base URL (/).

1 Comment

Perfect! This helped me solve my issue. Thaanks.
3

You can also try to use '/static/images/security-team.jpg' without import if you place your image in '/static/images/' folder. For example:

const styling = {
  backgroundImage: "url('/static/images/security-team.jpg')",
  width:"100%",
  height:"100%"
}
return (
  <div className="team" style={styling}></div>
);

1 Comment

Module not found: Error: Can't resolve '/static/images/security-team.jpg'
3

You can put the image in the public folder, and access it like so:

const team = (props) => {
const styling = {
    backgroundImage: `url('./security-team.jpg')`,
    width:"100%",
    height:"100%"
}
return (
    <dev className="team" style={styling}>

    </dev>
);

2 Comments

what is the public folder?
@Strubbl you should see a folder named public in the root of your project. It is on the same level as your src folder. It is automatically generated when you create a new project.
3

Next.js by default supports .scss and related files. Internally, Next.js uses a Webpack loader to load css that will follow url("") values and translate them to the output file name in the same way that import bg from '../../assets/images/security-team.jpg' will.

So as long as you're importing your css in a way that Webpack can understand import styles from './MyModule.module.scss' or similar, you can directly url('relative/path').

For example:

.team {
  background-image: url('../../assets/images/security-team.jpg'),
  width: 100%,
  height: 100%
  /* ... */
}

And the above does NOT require it to be in the public folder

Comments

1

the /static directory was deprecated. anyone who tries to use it will probably get the error message in their console but here the link containing NextJS' explanation of why they chose to deprecate the static directory.

Because public also covers the static directory use case we have decided to deprecate the static directory in favor of creating a public/static folder with the same functionality.

Comments

1

image must be in public (example with tailwind)

<div className="my-5 lg:my-6">
 <img src="/logotipo/logo.png" alt="easybanklogo" />
</div>

Comments

1

for use dynamic image

first of all declare style like this

 let style = {
        backgroundImage: "url(" + props.image + ")",
    }

then

<div style={style}>
    <div className="content">content here</div>
</div>

Comments

1

What I noticed in next js :

  • you can access files in the public folder direcly by including it's path from the public folder (not including the public folder or a route to that public folder ) for and inline BackgroundImage => "/image.png"

for and background-image(In a css file) => define a path from the file your coding in to that image eg "../public/image.png"

Back to what i was working on ...

  <section style={{ backgroundImage : "url('/4.jpg')" }}>

Comments

0
 <div
  class="horizontal-layout horizontal-menu navbar-static dark-layout 1-column footer-static bg-full-screen-image  blank-page blank-page"
  data-open="hover"
  data-menu="horizontal-menu"
  data-col="1-column"
  data-layout="dark-layout"
  style={{ backgroundImage: "url(/assets/images/pages/auth-bg.jpg)" }}
>

Comments

0

in next.js 14 with tailwind

    import imagePath from "public/image.png"
    
    // inset-0 makes it fill the entire space within its parent container.
    <div className="absolute -z-10 inset-0">
              <Image
                src={imagePath}
                alt="always add alt"
                fill
                style={{objectFit:'cover'}}
              />
              {product.title}
       </div>

available props

Comments

-1
<div className="VistaCodeLab" style={{backgroundImage: ` url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAANyUlEQVR4nO3baVRU1wEHcGzaNE2bpkk09qAxqFRR3AARUTFookZZ3IJI2NyiqIALZdFIghIZrAtuOWqsApqgSWwFberCMjMsAyMDzMISAZe4IYrKsMzy7n3z7wekzUlVZmAGo7m/c+4XnXe3/7w3j3fvs7JiGIZhGIZhGIZhGIZhGIZhGIZhGIZhGIZhGIZhGIZhGIZhnl0AergFrJo7bOrsKcYe4xm9fWV/F7cRluzXL5Jb8GqP2NxbMoGcg4vPkqXGHhd6XHpaoCB8yOGctL+MnTjEkn38RXD0Cpy85qRKIpBzaC8mB/LwuEQ5oSEpouSBru62luzzc8nBM8h1TbpK+OMguhrIj4LhlqeIDgwZN/ltS47huTDGO3B0RIby348KwlyB/DcYBdH5JqTu6TtoZB9LjumZ1N/FbUToMek/ExXE8KQwzBnI/wpp9RWkbHtz2LDelhzjM2GQk7tdyOGcNIGC8B1NXKKCPJgvSI17bcCAV02pP+x40fFEOaFG1N80X3AkoY+d3RuWHPPP0uAxE/uHpIiSBXJCjA3CZtSoP3WmLZ+4Xf18Y3c6d1d7z5S+g0b2WZ4iOiBQEH13TUxc0e2xAHpYWVlZDXR1tzU2mHipusE7avu6nj0Hv2Ke0f+MvDlsWG9fQepOgYJou/MbOmNF5J8XbTk0+Kf/blIwRerb3lE7IqytrV/uan+euj52dm/MF6QmCuSk9WlcKuIL69/z8fF54XH/b1owjTe8o3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rvI2p06QgTqokzh4fvte1GXpK7O3tX/SOSVoaL228ZuwtojHvb8zbdf7g1jINdsk1mHG+FbOyWjErsxVTzrbigFKDfUot1h48vbejekwJIjb3lswteLWHeWbmKbOxsXnJKzopzJhdKcYE07v3iN9vEt2pPKTSwF/YimlnWjD1u2b45bTiSLkG+wpvKPv2df3d4443JYgN4jrFhKDw2U9l84KlWVtbv+wZtSMyXqpu6GowtmO9HNPKNbo1+S2YebYZ3measSq/BV9XabV+67c98j1EJy//qWvTlWKjzghxXaVbYPj85zKIn+rZc/ArvolHPklUkAddCWZuxM41ggstWCFswkpxMxIutCBqy+crlm5Ls5u+cF2v9s85eflPNWb1UyBv2wA3IWBV0M9yA5yl9Rs+/LX5giMJxmw5bQ+mj+2Ivu3HA+gxdvYi/9GzFyxymb140Tvzlvi1f6MD4w/2n7Z6s4exQbRvEbXEU+BnTu+BI970FaRsS5QTTUcTZ8obVBHpqn8ZEcQN76gdofb29i9acozPpL6DRvYJTPp275M2pJnrlbb21wxsbGxesuSYngttOwWFf3/UIllXA2l/Ead3796/t+QYnksDXd1tQ5JzvvrxIlmn31N/uMn7dVtbk3YrMo9g6+I2tH2RzNRATNnkzZho5PS5DkPGTzd699/kpTE+f7Z16NXxJxmGYRiGYRiGYRiGYRiGYRiGYRiGYRiGYRiGYRiGYX6J/gPRW+oYDGDMNAAAAABJRU5ErkJggg==')`}}></div>

use like this with base64 image

Online conversion tool for image to base64 https://www.base64-image.de/

1 Comment

You can't load large images in base64!
-2

I managed to get around this by using the src property of the image object so:

{ img.src }

Their documentation shows a background image implemented via the below method though:

import Image from 'next/image'
<Image />

Here's a live demo - https://image-component.nextjs.gallery/background

1 Comment

The next/image package returns a severely opinionated element, the question is about simply using the asset path string in your code as you need.
-2
Example using Nextjs, node modules and scss.

    import styles from "../styles/Home.modules.scss"
    import Image from "next/image"
    export default function Home() {
      <div className={styles.background_image}> 
        <Image
          width={2746}  //use the width of the image being used
          height={4681} //use the height of the image being used
          layout="fill"
          alt="water_portrait"
          src="/home/water_portrait.jpg" //image saved in public/home
        />
      </div>
   }

  //styles/Home.module.scss
  .background_image {
    position: absolute;
    top: 0;
    left: 0;
    width: 100vw;
    height: 100vh;
    z-index: 1;
  }
  .somethingElse{
      positsion: relative;
      z-index:10;
  }

Comments

-2

Next.js can serve static files, like images, under a folder called public in the root directory. Files inside public can then be referenced by your code starting from the base URL (/).

For example, if you add an image to public/me.png, the following code will access the image:

background-image: url('/img/imge1.png');

1 Comment

This assumes you're loading from /, if you load from a subpath, it will be wrong!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.