Next.js background-image css property cant load the image
Solution 1
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>
Solution 2
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;
}
Solution 3
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
Solution 4
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');
Solution 5
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');
Hassan Kandil
Updated on February 04, 2022Comments
-
Hassan Kandil about 2 years
The issue simply is 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 ( <dev className="team" style={styling}> </dev> );
}
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 !