Reputation: 79
I am trying to add a background image to Box component of mui but it dosen't work I am providing my code
const Main = () => {
return (
<Box
sx={{backgroundImage:'images/cover.jpeg'}}
height='385px'
>
</Box>
)
}
Upvotes: 7
Views: 21669
Reputation: 131
You are well on track. To employ this successfully, you can proceed as follows;
import cover from "./images/cover.jpeg";
const Main = () => {
return (
<Box
sx={{
backgroundImage:`url(${cover})`,
backgroundRepeat: "no-repeat",
backgroundSize: "cover",
height: "385px",
}}
>
</Box>
)
}
The assumption here is that the path provided for the import is correct("./images/cover.jpeg"). You can supply additional styling such as width to the image as desired.
Upvotes: 10
Reputation: 21
What worked for me was:
<Box sx={{
backgroundImage: `url(${calltoActionBg.src})`,
}}>CallToAction</Box>
Without the ".src" it was rendering as [Object,Object]
Upvotes: 2
Reputation: 13462
You're not far from it. You just need to add the path to the file preceded by url
, for example:
const Main = () => {
return (
<Box
sx={{
backgroundImage: "url('images/cover.jpeg')",
backgroundRepeat: "no-repeat",
height: '385px',
width: '385px'
}}
>
</Box>
);
};
(assuming images/cover.jpeg
is the correct path to your image.)
Working CodeSandbox: https://codesandbox.io/s/mui-box-background-image-wcseex?file=/demo.js
Upvotes: 5
Reputation: 884
const Main = () => {
return (
<Box
sx={{
backgroundImage: `url("./images/cover.jpeg")`,
backgroundPosition: `right bottom`,
backgroundRepeat: `no-repeat`,
backgroundSize: `300px 300px`,
height: "100%",
width: "100%",
}}
>
</Box>
)
}
Make sure image url is correct and need to give some size to adjust the layout
Upvotes: 1