Ad

How To Add Background Image On A Material Ui Dialog Component

I'm using material-ui version 3.9.3 in my React application. I want to add a background image on a dialog. I'm using the Dialog component for it but I'm unable to add a background image on the whole dialog. For example:


    <Dialog
       fullScreen={fullScreen}
        open={this.props.open}
        onClose={this.handleClose}
        aria-labelledby='responsive-dialog-title'
        >
        <DialogTitle
          id='customized-dialog-title'
          onClose={this.handleClose}
          noCloseButtonNeeded={noCloseButtonNeeded}
        >
          {/* some jsx */}
         </DialogTitle>
        <DialogContent>
          {children}
        </DialogContent>
      </Dialog>

I have tried to add an image using classes and custom CSS but I'm unable to do it. Can anyone help me out to add it? Thanks in advance :)

Ad

Answer

First, you can define the background image in a styles object that can be used with the withStyles higher-order component to apply it to the dialog:

const styles = {
  dialog: {
    backgroundImage: "url(https://i.imgur.com/HeGEEbu.jpg)"
  }
};

When you pass this object to the withStyles HOC, it will supply your component with a classes prop containing properties with the same names as the properties on styles that you've defined.

Next, you can apply this class to the Dialog by taking advantage of the classes prop (the specific overrides made available for the Dialog component are detailed here):

<Dialog ... classes={{paper: classes.dialog}}>
        {/* ... */}
</Dialog>

This is telling material-ui to merge the styles you have defined in styles.dialog with the default styles on the Paper element that is used with the Dialog.

You'll need to make sure that you're wrapping your component in the withStyles HoC. If you have a class component, it will look something like this:

export default withStyles(styles)(DialogWithBackgroundImage);

For functional components, it would look something like:

export default withStyles(styles)(({open, children, classes}) => (<Dialog ...></Dialog>))

Here's a working example that ties everything together: https://codesandbox.io/embed/q3zy4r2np4

Ad
source: stackoverflow.com
Ad