Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Next.js background-image css property cant load the image

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 !

like image 640
Hassan Kandil Avatar asked Aug 14 '18 13:08

Hassan Kandil


People also ask

Why can't I set a background image in CSS?

Make sure the image path is set correctly in the background-image url. Once you have made sure that your CSS file is linked correctly, also check that the image itself is set correctly. Again, you will want to open your code inspector in the browser to check.

How do I add a background image in next JS?

Firstly import the image component in next. js and define the image path in src props in the image component. Now your image shows in the browser. js, by default, provides all functionality.


1 Answers

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');
like image 164
Peter W Avatar answered Sep 20 '22 04:09

Peter W