Pratik Shinde
Pratik Shinde

Reputation: 79

how to add background image to box in mui

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: 21672

Answers (4)

Steve Austin
Steve Austin

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

Kelvin Orhungul
Kelvin Orhungul

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

Steve G
Steve G

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

Thusithz
Thusithz

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

Related Questions