Is there a way to position a ListItem (using React) in the lower left corner in this specific case?

import * as React from 'react';
import { styled, useTheme } from '@mui/material/styles';
import Box from '@mui/material/Box';
import MuiDrawer from '@mui/material/Drawer';
import MuiAppBar from '@mui/material/AppBar';
import Toolbar from '@mui/material/Toolbar';
import List from '@mui/material/List';
import CssBaseline from '@mui/material/CssBaseline';
import Typography from '@mui/material/Typography';
import Divider from '@mui/material/Divider';
import IconButton from '@mui/material/IconButton';
import MenuIcon from '@mui/icons-material/Menu';
import ChevronLeftIcon from '@mui/icons-material/ChevronLeft';
import ChevronRightIcon from '@mui/icons-material/ChevronRight';
import ListItem from '@mui/material/ListItem';
import ListItemButton from '@mui/material/ListItemButton';
import ListItemIcon from '@mui/material/ListItemIcon';
import ListItemText from '@mui/material/ListItemText';
import HomeIcon from '@mui/icons-material/Home';
import SchoolIcon from '@mui/icons-material/School';
import ClassIcon from '@mui/icons-material/Class';

const drawerWidth = 240;
const icons = [<HomeIcon/>, <ClassIcon/>,<SchoolIcon/>]

const openedMixin = (theme) => ({
  width: drawerWidth,
  transition: theme.transitions.create('width', {
    easing: theme.transitions.easing.sharp,
    duration: theme.transitions.duration.enteringScreen,
  }),
  overflowX: 'hidden',
});

const closedMixin = (theme) => ({
  transition: theme.transitions.create('width', {
    easing: theme.transitions.easing.sharp,
    duration: theme.transitions.duration.leavingScreen,
  }),
  overflowX: 'hidden',
  width: `calc(${theme.spacing(7)} + 1px)`,
  [theme.breakpoints.up('sm')]: {
    width: `calc(${theme.spacing(8)} + 1px)`,
  },
});

const DrawerHeader = styled('div')(({ theme }) => ({
  display: 'flex',
  alignItems: 'center',
  justifyContent: 'flex-end',
  padding: theme.spacing(0, 1),
  // necessary for content to be below app bar
  ...theme.mixins.toolbar,
}));

const AppBar = styled(MuiAppBar, {
  shouldForwardProp: (prop) => prop !== 'open',
})(({ theme, open }) => ({
  zIndex: theme.zIndex.drawer + 1,
  transition: theme.transitions.create(['width', 'margin'], {
    easing: theme.transitions.easing.sharp,
    duration: theme.transitions.duration.leavingScreen,
  }),
  ...(open && {
    marginLeft: drawerWidth,
    width: `calc(100% - ${drawerWidth}px)`,
    transition: theme.transitions.create(['width', 'margin'], {
      easing: theme.transitions.easing.sharp,
      duration: theme.transitions.duration.enteringScreen,
    }),
  }),
}));

const Drawer = styled(MuiDrawer, { shouldForwardProp: (prop) => prop !== 'open' })(
  ({ theme, open }) => ({
    width: drawerWidth,
    flexShrink: 0,
    whiteSpace: 'nowrap',
    boxSizing: 'border-box',
    ...(open && {
      ...openedMixin(theme),
      '& .MuiDrawer-paper': openedMixin(theme),
    }),
    ...(!open && {
      ...closedMixin(theme),
      '& .MuiDrawer-paper': closedMixin(theme),
    }),
  }),
);

export default function MiniDrawer({children}) {
  const theme = useTheme();
  const [open, setOpen] = React.useState(false);
  
  const handleDrawerOpen = () => {
    setOpen(true);
  };

  const handleDrawerClose = () => {
    setOpen(false);
  };
  
  return (
    <Box sx={{ display: 'flex' }}>
      <CssBaseline />
      <AppBar position="fixed" open={open}>
        <Toolbar>
          <IconButton
            color="inherit"
            aria-label="open drawer"
            onClick={handleDrawerOpen}
            edge="start"
            sx={{
              marginRight: 5,
              ...(open && { display: 'none' }),
            }}
          >
            <MenuIcon />
          </IconButton>
          <Typography variant="h6" noWrap component="div">
            NOPF
          </Typography>
        </Toolbar>
      </AppBar>
      <Drawer variant="permanent" open={open}>
        <DrawerHeader>
          <IconButton onClick={handleDrawerClose}>
            {theme.direction === 'rtl' ? <ChevronRightIcon /> : <ChevronLeftIcon />}
          </IconButton>
        </DrawerHeader>
        <Divider />
        <List>
          {['Home', 'Klasse', 'Schule'].map((text, index) => (
            <ListItem key={text} disablePadding sx={{ display: 'block' }}>
              <ListItemButton
                sx={{
                  minHeight: 48,
                  justifyContent: open ? 'initial' : 'center',
                  px: 2.5,
                }}
              >
                <ListItemIcon
                  sx={{
                    minWidth: 0,
                    mr: open ? 3 : 'auto',
                    justifyContent: 'center',
                  }}
                >
                  {icons[index]}
                </ListItemIcon>
                <ListItemText primary={text} sx={{ opacity: open ? 1 : 0 }} />
              </ListItemButton>
            </ListItem>
          ))}

          <ListItem disablePadding sx={{ display: 'block', position: 'absolute', bottom: 0, left: 0 }}>
            <ListItemButton
              sx={{
                minHeight: 48,
                justifyContent: open ? 'initial' : 'center',
                px: 2.5,
              }}
            >
              <ListItemIcon
                  sx={{
                    minWidth: 0,
                    mr: open ? 3 : 'auto',
                    justifyContent: 'center',
                  }}
              >
                <HomeIcon/>
              </ListItemIcon>
              <ListItemText primary={'Profil'} sx={{ opacity: open ? 1 : 0 }} />
            </ListItemButton>
          </ListItem>

        </List>
      </Drawer>
      <Box component="main" sx={{ flexGrow: 1, p: 3 }}>
        <DrawerHeader />
        {children}
      </Box>
    </Box>
  );
}

This is a modified version of the original code snippet provided by the MaterialUI website, in which I added a ListItem at the bottom left corner of the Drawer. The positioning of this new ListItem has been adjusted using "position: absolute" to make it stick to the bottom of the Drawer and prevent unintended clicking when hovering over its area. This solution ensures consistent behavior regardless of device width.

Answer №1

If you want to properly position the items in a drawer, I recommend utilizing the flex CSS. By using the flex CSS property, you can ensure that the list occupies all the vertical space within the drawer. Additionally, employing the margin-top attribute with the value of auto will help push the last item to the bottom corner of the drawer. For a practical application, I made adjustments to the basic drawer example provided in MUI documentation.

const DrawerList = (
  <Box sx={{ display: 'flex', flexDirection: 'column', flex: 1, width: 250 }} role="presentation" onClick={toggleDrawer(false)}>
    <List sx={{ display: 'flex', flexDirection: 'column', flex: 1 }}>
      {['All mail', 'Trash', 'Spam'].map((text, index) => (
        <ListItem key={text} disablePadding>
          <ListItemButton>
            <ListItemIcon>
              {index % 2 === 0 ? <InboxIcon /> : <MailIcon />}
            </ListItemIcon>
            <ListItemText primary={text} />
          </ListItemButton>
        </ListItem>
      ))}
      <ListItem disablePadding sx={{ marginTop: 'auto' }}>
        <ListItemButton>
          <ListItemIcon>
            <AccountCircleIcon />
          </ListItemIcon>
          <ListItemText primary="Last item" />
        </ListItemButton>
      </ListItem>
    </List>
  </Box>
);

To see this implementation in action, feel free to view the complete example on StackBlitz.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieving and securely storing information using fetch() on authenticated REST services

Currently, I have successfully set up a React application that communicates with a REST backend which is built using Python and Flask. The specific functionality I have achieved involves downloading data from a database and saving it as a CSV file through ...

css side by side with immovable element

Seeking assistance with CSS. I am looking to create a layout as follows: I want a center-fixed menu with a width of 960px - this part is straightforward. Alongside the menu, I aim to have two divs: one spanning from the left edge of the screen to the cl ...

Error encountered in Next.js: The function 'useLayoutEffect' was not successfully imported from 'react' (imported as 'React')

I've been in the process of migrating an application from CSR (using webpack only) to SSR, and I'm utilizing Next.js for this transition. Following the migration guide provided by Next.js for switching from vite (specifically focusing on parts r ...

The tab component is failing to load due to an issue with the Bootstrap tab

I've created a page displaying different locations with two tabs - one for Google Maps and another for weather. For example, take a look at this location: The issue I'm facing is that when switching between the tabs, they don't load fully. ...

Place a button in relation to the top of its parent element

I am trying to display control buttons at the top of a table cell when hovering over an image within the cell. Here is the HTML structure I have: <table id="pridat_fotky"> <tbody> <tr> <td class=" ...

Retrieving information from an array and displaying it dynamically in Next.js

I've been diving into the Next.js framework lately and I've hit a roadblock when it comes to working with dynamic routes and fetching data from an array. Despite following the basics of Next.js, I'm still stuck. What am I looking for? I ne ...

Aligning a child div within a parent div using HTML/CSS where the child div takes up 30% of the parent div and

Can anyone help me figure out why these two INPUT elements aren't aligning next to each other? I appreciate any assistance you can offer! <STYLE> html, body { width: 100%; height: 100%; margin: 0px; padding: 0px; } </STYLE& ...

What is the correct way to include a new property in the MUI Link component using TypeScript?

Currently, within my mui-theme.ts configuration file, I have the following setup: const theme = createTheme(globalTheme, { components: { MuiLink: { variants: [ { props: { hover: 'lightup' }, style: { ...

The background color of the CSS div tag does not cover the entire axis

I'm facing a dilemma in my CSS design that's got me stuck. This issue also seems to be present in this forum: Whenever I zoom in on the page, I noticed that the header background doesn't fully extend across the screen horizontally. Here&apo ...

Tips for sending props to Material UI components

Hey there! I'm currently working on a progressbar component that utilizes animations to animate the progress. I've styled the component using Material UI classes and integrated it into another component where I pass props to customize the progres ...

Can passing parameters between nested map functions cause any issues?

While attempting to navigate to a page in reactjs and pass parameters using the useNavigate hook, I encounter an unexpected token error as soon as I include the navigation within the anchor tag. <a onClick={() ={ ...

How far apart are two surfaces when they are rotated along the Y-axis

Access Code: Click here to access the code I am trying to make sure that the red surface lies completely flat on top of the gray surface. However, there seems to be a gap (marked ??) between the two surfaces when I rotate 'modifier1'. How can I ...

How can I expand the notification pop-up in R Shiny?

I'm trying to figure out how to expand the notifications in R Shiny because right now they are cutting off longer error messages. Any suggestions? library(shiny) ui <- fluidPage( actionButton("test", "Test") ) server <- f ...

Error due to undefined property when using UseEffect and thunk in react-redux

As I delve into learning react-redux-rails through the construction of a simple todo list application, I find myself grappling with the complexities of Redux and its requirements. Currently, my focus is on fetching a list of Todos from the database and ren ...

Attempting to align a FieldSet in the middle of the page

Having trouble aligning a field set within a div. The first two elements are centered right next to each other, but the third one is justified left and I'm struggling to center it within the div. JSP <tr> <th> <span onclick="toggleDiv ...

Struggling to resolve this npm installation issue post Windows 11 update - any suggestions?

After recently upgrading to Windows 11 and Visual Studio 2022, I encountered a series of errors during the npm install process when trying to install an app that was previously functional on Windows 10. This particular app serves as the UI for a website ...

"Maximizing battery life: Efficient video playback on iOS in low power

Summary: I am currently working on a website that features a video set as the background which autoplays. However, I have encountered an issue on iOS devices when "Low Power Mode" is activated - the video fails to play and instead displays a large "Play" i ...

What are the most effective methods for utilizing React child components?

I have a particular interest in how to efficiently pass information along. In a different discussion, I learned about the methods of passing specific props to child components and the potential pitfalls of using <MyComponent children={...} />. I am ...

Limit the results of the React API and explore additional items with the option to

For my page, I am working on conditional rendering to restrict the number of items a user can view in a component to 5. However, I also want to provide users with the option to see all items when they click on a 'more' button. I attempted to inc ...

Upgrade from react-router v5 to v6 for dynamic navigation between tabs

I am facing issues while updating to react router v6 in my shared component with tab navigation. The URL structure is as follows: domain.com/home/:tab domain.com/settings/:tab I have a base route like home, settings,... and the tab name is appended at t ...