Material UI > Backdrop > only for some subcomponent of the page

Viewed 5576

Is there any way how to enhance a backdrop from example in https://material-ui.com/components/backdrop/ to show loading circle only above the single component (in case some page has more component), not above the whole page?

Thanks for reply.

2 Answers

Backdrop are fixed positioned by default, that's why it covers the whole page.

To achieve the result you want, we have to change its position to absolute and contain it inside an element with relative position — this element can be your component. If you're new in CSS positions check this docs from developer.mozilla.org.

Knowing all that, we can come up with the following codes

const useStyles = makeStyles({
  parent: {
    position: "relative",
    width: 200,
    height: 200,
    backgroundColor: "red",
    zIndex: 0,
  },
  backdrop: {
    position: "absolute"
  }
});

export default function App() {
  const classes = useStyles();

  return (
    <div className={classes.parent}>
      <Backdrop className={classes.backdrop} open={true}>
        <CircularProgress color="inherit" />
      </Backdrop>
    </div>
  );
}

Also we have to define z-index on either parent or backdrop element to make it work. Not sure why though.

I created a codesandbox for you to play with.

Edit lively-wind-47fk4

The Backdrop component of Material UI is set to position: 'fixed' by default, that's why it covers the whole page.

If you want it to reside and position itself like any other component typically on the DOM, all you have to do is to reset its position back to relative, for instance:

<Backdrop open={true} sx={{ position: 'relative' }}>
   <CircularProgress color="inherit" />
</Backdrop>

and you don't need to change the parent component since it should be in your case see to relative by default if you're not changing it. But if you have crazy positions going in your app here and there, then you might consider changing that as well.

Related