Search code examples
cssreactjsgrommet

Show image as background in box in grommet


I am trying to set the background of a Box to a local image using the url property for background but it doesn't seem to take effect. I have created a sandbox to showcase the problem. I have added a background.jpeg image locally which I am setting as the background on the box but the background image is not set as the background. If I set the background image to some color say "blue", it takes affect.

How can I set the background of a Box to an image?

https://codesandbox.io/s/great-sun-tqmhb


Solution

  • You can move your image to public folder and change your code like so :-

    import "./styles.css";
    import { Grommet, Box } from "grommet";
    export default function App() {
      return (
        <Grommet>
          <Box
            background="url('background.jpeg')"
            height="200px"
            width="200px"
            border={{ color: "brand", size: "large" }}
          />
        </Grommet>
      );
    }
    

    Explanation : The place from where your index.html is served is the base path of your application (as per the webpack config done by CRA internally). It's relative to this base path you can target retrieving the assets.

    Codesandbox Link