Search code examples
reactjsscrollmaterial-ui

Grid item not shrinking to fit the contained Scrollable List


I am trying to get the grid item containing the scrollable list to shrink so the back button is just below the list.

Following is the code, and a link to CodeSandbox. There is a lot of grid and box components surrounding the list. These are extracts from other parent components so I get it all in one file for simplicity.

https://codesandbox.io/s/y2c9sn?file=/src/App.js

import * as React from "react";
import {
  Box,
  Button,
  Grid,
  List,
  ListItem,
  ListItemText,
  ListItemButton,
  AppBar,
  Toolbar,
  Typography,
} from "@mui/material";

const usersList = [
  "user1",
  "user2",
  "user3",
  "user4",
  "user5",
  "user6",
  "user7",
  "user8",
  "user9",
  "user10",
];

function App() {
  return (
    <Box
      sx={{
        display: "flex",
        justifyContent: "center",
        height: "100vh",
      }}
    >
      <Grid container justifyContent="center">
        <Grid item xs={12} md={8}>
          <AppBar position="static">
            <Toolbar>
              <Typography variant="h6">Scrollable List</Typography>
            </Toolbar>
          </AppBar>
        </Grid>

        <Grid item xs={12} md={8}>
          <Box>
            <Grid container justifyContent="center">
              <Grid item xs={12}>
                <List sx={{ maxHeight: "50%", overflow: "auto" }}>
                  {usersList.map((user, index) => {
                    return (
                      <ListItem disablePadding key={index}>
                        <ListItemButton>
                          <ListItemText>{user}</ListItemText>
                        </ListItemButton>
                      </ListItem>
                    );
                  })}
                </List>
              </Grid>
            </Grid>
            <Grid container justifyContent="center">
              <Grid item xs={8}>
                <Button
                  name="back"
                  variant="contained"
                  color="primary"
                  value="back"
                  fullWidth
                  size="small"
                >
                  Back
                </Button>
              </Grid>
            </Grid>
          </Box>
        </Grid>
      </Grid>
    </Box>
  );
}

export default App;

Link to CodeSandbox https://y2c9sn.csb.app/


Solution

  • You can move this style:

    sx={{ maxHeight: "50%", overflow: "auto" }}
    

    from your List component to its first parent Grid container.

    This sandbox is the updated version of your sandbox with this change.