Search code examples
cssreactjsiconsbackground-imagefluent-ui

Background Image Not Displaying in React App


I am trying to use a background image of an upload icon in my video cards within my React app, but so far have been unable to get the background image to display. I see the background color I have declared, but not the background image, and I'm not sure why. Here is the relevant code block:

    <Card.Section
      fill
      styles={{
        ...backgroundImageCardSectionStyles,
        root: {
          ...backgroundImageCardSectionStyles.root,
          backgroundImage: '../../assets/images/upload.png',
          backgroundColor: '#f3f2f1',
          minHeight: '150px',
          maxHeight: '150px',
        },
      }}
      ... more code

I also tried pulling the icon is an an import, like so:

import { uploadIcon } from '../../assets/images/upload.png';

... and then using it like this:

   <Card.Section
      fill
      styles={{
        ...backgroundImageCardSectionStyles,
        root: {
          ...backgroundImageCardSectionStyles.root,
          backgroundImage: uploadIcon,
          backgroundColor: '#f3f2f1',
          minHeight: '150px',
          maxHeight: '150px',
        },
      }}
      ... more code

But that also didn't work.

By the way, my backgroundImageCardSectionStyles referenced above looks like this:

const backgroundImageCardSectionStyles = {
  root: {
    backgroundPosition: 'center center',
    backgroundSize: 'cover',
    height: 144,
  },
};

What am I missing here?


Solution

  • Try using url in your CSS when you are setting the background. The url() is used to include a file in CSS.

     import UploadIcon from "../image.png"
    
     <Card.Section
          fill
          styles={{
            ...backgroundImageCardSectionStyles,
            root: {
              ...backgroundImageCardSectionStyles.root,
              backgroundImage: `url(${UploadIcon})`,
              backgroundColor: '#f3f2f1',
              minHeight: '150px',
              maxHeight: '150px',
            },
          }}
          ... more code