Search code examples
reactjsmaterial-uiflexboxgrid

MUI Grid2 container not taking up remaining space


I am trying to create a React layout as shown in the code sandbox project

Edit MUIUserInterface

Image Layout(https://i.sstatic.net/WimVbK3w.png)

I expect the grid layout will occupy the area indicated by the line.

I want the left grid to have a constant width of 216px even for smaller screen width, that is why I have not used something like 2:10 for width for the main section.

Can you please help me to identify what I am missing?

To have the inner grid stretch I have tried below. But this also does not seem to work.

<Grid2 container direction="column" alignItems={"stretch"}>


Solution

  • In short, it is important to define the root parent as Grid2 with a specified size (which must be larger than all child ones) for child Grid2s to calculate the correct occupied space. Both hierarchy and the use of the size property are important.

    Specifically, you can use size="grow" for most components to grow until the width of the display.

    Working image of the expected display


    Below are the workable codes of your expected display:

    import { Grid2, ListItem } from "@mui/material";
    import TopBar from "./TopBar1";
    import VideoSummary from "./VideoSummary";
    
    const preview = [...new Array(15)].map((_, index) => <h5>Hello {index}</h5>);
    
    export default function YouTubeHome() {
      return (
        <Grid2 container direction="column" size={40}>
          <Grid2 color="blue" size="grow">
            <TopBar></TopBar>
          </Grid2>
          {/* REMARK: Remove the nowrap if you want the right-side grid to wrap under when not enough space. */}
          <Grid2 container direction="row" wrap="nowrap">
            <Grid2
              container
              minWidth="216px"
              direction="column"
              sx={{ bgcolor: "yellow" }}
            >
              <ListItem sx={{ bgcolor: "blue" }}>Your Videos</ListItem>
              <ListItem sx={{ bgcolor: "green" }}>Your Movies & TV</ListItem>
              <ListItem sx={{ bgcolor: "orange" }}>Test</ListItem>
            </Grid2>
            <Grid2 container sx={{ bgcolor: "pink" }}>
              {preview.map((text, index) => (
                <Grid2 sx={{ bgcolor: "red" }} size={3}>
                  <VideoSummary
                    key={index}
                    Text={text}
                    Even={index % 2 == 0}
                  ></VideoSummary>
                </Grid2>
              ))}
            </Grid2>
          </Grid2>
        </Grid2>
      );
    }
    

    Edit MUIUserInterface (forked)

    P.S. Use as few Grid2s as possible, as too many will confuse you.