0

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

Varun Gupta
  • 2,870
  • 6
  • 33
  • 73

1 Answers1

2

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

Lakshya Thakur
  • 8,030
  • 1
  • 12
  • 39
  • Great, it worked. Thanks! Just a follow-up question. I have created an npm package that contains all the images which is then used by the mobile app and the web app. I am using a monorepo to manage various packages in the repository. Is there a way to point to an image present in an npm package using `url` or is that not possible? – Varun Gupta Mar 19 '21 at 06:54
  • I think unless the npm package ensures that the images get served from the same path from where the app is running, it's not possible as it is. Your npm package though can be run in a separate server kind of acting like a CDN for your mobile or web app. Also I haven't personally handled such a scenario so I might have less knowhow on the same. – Lakshya Thakur Mar 19 '21 at 07:01
  • I think `url` probably looks at the public path as you mentioned and doesn't consider npm packages. I tried many combinations but none of them worked. Thanks for your original answer answer. That was really helpful. – Varun Gupta Mar 19 '21 at 11:56