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.
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`,
}}
/>