Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to set Background Image in Nextjs?

I’m using Nextjs and Material-Ui in my project, setting background image is not working as it did in other projects with react. It’s my first time using Nextjs.
I’ve tried importing Image from "next/image" and using the
<Image height={} width={} />
but it’s not working like background! I’d appreciate if you have any information about setting background in Nextjs with MUI.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Short answer: In fact, the path to the image is a relative path, and
the goal is to get the absolute path of the image.

To import the image as a background Image in NextJS page can be applied by various methods, but in this case, importing as an image file maybe is more suitable.

import myImage from "../public/imageName.png";

After the code is compiled the myImage will have an object that is considered the details of an image such as "src", "height", "width", and "blurDataURL".

Here is an example of what the object looks like.

{
    "src": "/_next/static/media/imageName.7f7cc385.png",
    "height": 7730,
    "width": 7730,
    "blurDataURL": "/_next/image?url=%2F_next%2Fstatic%2Fmedia%myImage.7f7cc385.png&w=8&q=70"
}

Finally, this can have a direct access to the image’s absolute path via the src property of myImage object. By using the src property of the myImage, the following code demonstrates how to display an image located in the public folder by MUI Box Component.

<Box
    height={789}
    width={1440}
    sx={{
      background: `url(${myImage.src}) center / cover`,
    }} 
/>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading