OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

MUI Drawer Component is not closing when any button inside is clicked for the very first time

  • Thread starter Thread starter Piyush Keshari
  • Start date Start date
P

Piyush Keshari

Guest
I have a sidebar for the navigation links in mobile view. I am facing issue that when the ListItem buttons are clicked for the very first time when the page is loaded. It is setting the mobileMenuOpen to false (I can see that in the useEffect console.log()) but the drawer is not closing. When I click same button for the second time console.log() is not done obviously because value was already changed on the first click but this time the drawer is closing.

Header.jsx

Code:
export default function Header() {
    const { totalOrderItems } = useCartContext();
    const location = useLocation();
    const theme = useTheme();
    const isDesktop = useMediaQuery(theme.breakpoints.up('lg'));

    const [mobileMenuOpen, setMobileMenuOpen] = useState(false);

    useEffect(() => {
        console.log('mobileMenuOpen is set to:', mobileMenuOpen);
    }, [mobileMenuOpen]);

    const isActive = (path) => {
        return location.pathname.toLowerCase() === path ? 'primary' : 'default';
    };

    const sidebarMenu = (
        <List sx={{ width: 200 }}>
            <ListItemButton component={NavLink} to="/" color={isActive('/') || isActive('/home')}>
                <ListItemText primary="Home" onClick={() => setMobileMenuOpen(false)} />
            </ListItemButton>
            <ListItemButton component={NavLink} to="/gift-card" color={isActive('/gift-card')}>
                <ListItemText primary="Gift Card" onClick={() => setMobileMenuOpen(false)} />
            </ListItemButton>
            <ListItemButton component={NavLink} to="/shop" color={isActive('/shop')}>
                <ListItemText primary="Shop" onClick={() => setMobileMenuOpen(false)} />
            </ListItemButton>
            <ListItemButton component={NavLink} to="/about-us" color={isActive('/about-us')}>
                <ListItemText primary="About Us" onClick={() => setMobileMenuOpen(false)} />
            </ListItemButton>
            <ListItemButton component={NavLink} to="/gallery" color={isActive('/gallery')}>
                <ListItemText primary="Gallery" onClick={() => setMobileMenuOpen(false)} />
            </ListItemButton>
        </List>
    );

    return (
        <Toolbar className='header' sx={{ position: 'fixed', top: 0, left: 0, right: 0, zIndex: 1100, backgroundColor: 'white' }}>
            <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', width: '100%' }}>
                <IconButton onClick={() => setMobileMenuOpen(true)} sx={{ display: { lg: 'none' } }}>
                    <MenuIcon />
                </IconButton>
                <Drawer
                    anchor="left"
                    open={mobileMenuOpen}
                    onClose={() => setMobileMenuOpen(false)}
                    sx={{
                        width: 200,
                        flexShrink: 0,
                        '&.MuiDrawer-paper': { width: 200, boxSizing: 'border-box' },
                        display: { lg: 'none', xs: 'block' }
                    }}
                >
                    {sidebarMenu}
                </Drawer>
                {
                    isDesktop &&
                    <NavLink to="/" style={{ display: 'block' }}>
                        <img src={`${import.meta.env.VITE_ASSETS_URL}/logo.webp`} alt="logo" style={{ height: '50px', width: 'auto' }} className='logo' />
                    </NavLink>
                }
                {
                    isDesktop &&
                    <Box sx={{ display: 'flex', justifyContent: 'center', flex: 1 }}>
                        <Box sx={{ display: 'flex', justifyContent: 'center', gap: 2 }}>
                            <Button variant='text' component={NavLink} to="/" color={isActive('/') || isActive('/home')} disableRipple
                                sx={{
                                    '&:hover': {
                                        background: 'none',
                                        color: 'primary.main',
                                    },
                                    '&:active': {
                                        background: 'none',
                                        color: 'primary.main',
                                    },
                                }}
                            >Home</Button>
                            <Button variant='text' component={NavLink} to="/gift-card" color={isActive('/gift-card')} disableRipple
                                sx={{
                                    '&:hover': {
                                        background: 'none',
                                        color: 'primary.main',
                                    },
                                    '&:active': {
                                        background: 'none',
                                        color: 'primary.main',
                                    },
                                }}
                            >Gift Card</Button>
                            <Button variant='text' component={NavLink} to="/shop" color={isActive('/shop')} disableRipple
                                sx={{
                                    '&:hover': {
                                        background: 'none',
                                        color: 'primary.main',
                                    },
                                    '&:active': {
                                        background: 'none',
                                        color: 'primary.main',
                                    },
                                }}
                            >Shop</Button>
                            <Button variant='text' component={NavLink} to="/about-us" color={isActive('/about-us')} disableRipple
                                sx={{
                                    '&:hover': {
                                        background: 'none',
                                        color: 'primary.main',
                                    },
                                    '&:active': {
                                        background: 'none',
                                        color: 'primary.main',
                                    },
                                }}
                            >About Us</Button>
                            <Button variant='text' component={NavLink} to="/gallery" color={isActive('/gallery')} disableRipple
                                sx={{
                                    '&:hover': {
                                        background: 'none',
                                        color: 'primary.main',
                                    },
                                    '&:active': {
                                        background: 'none',
                                        color: 'primary.main',
                                    },
                                }}
                            >Gallery</Button>
                        </Box>
                    </Box>
                }
                <Box>
                    <IconButton component={NavLink} to='cart' color={isActive('/cart')}>
                        <Badge badgeContent={totalOrderItems} color="secondary">
                            <ShoppingBagOutlinedIcon />
                        </Badge>
                    </IconButton>
                    <IconButton component={NavLink} to='profile' color={isActive('/profile')}>
                        <AccountCircleOutlinedIcon />
                    </IconButton>
                </Box>
            </Box>
        </Toolbar>
    );
}

Header.css

Code:
.header {
    height: var(--header-height);
    overflow: hidden;
    box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.1);
}

<p>I have a sidebar for the navigation links in mobile view. I am facing issue that when the ListItem buttons are clicked for the very first time when the page is loaded. It is setting the <code>mobileMenuOpen</code> to false (I can see that in the useEffect console.log()) but the drawer is not closing. When I click same button for the second time console.log() is not done obviously because value was already changed on the first click but this time the drawer is closing.</p>
<p><strong>Header.jsx</strong></p>
<pre class="lang-js prettyprint-override"><code>export default function Header() {
const { totalOrderItems } = useCartContext();
const location = useLocation();
const theme = useTheme();
const isDesktop = useMediaQuery(theme.breakpoints.up('lg'));

const [mobileMenuOpen, setMobileMenuOpen] = useState(false);

useEffect(() => {
console.log('mobileMenuOpen is set to:', mobileMenuOpen);
}, [mobileMenuOpen]);

const isActive = (path) => {
return location.pathname.toLowerCase() === path ? 'primary' : 'default';
};

const sidebarMenu = (
<List sx={{ width: 200 }}>
<ListItemButton component={NavLink} to="/" color={isActive('/') || isActive('/home')}>
<ListItemText primary="Home" onClick={() => setMobileMenuOpen(false)} />
</ListItemButton>
<ListItemButton component={NavLink} to="/gift-card" color={isActive('/gift-card')}>
<ListItemText primary="Gift Card" onClick={() => setMobileMenuOpen(false)} />
</ListItemButton>
<ListItemButton component={NavLink} to="/shop" color={isActive('/shop')}>
<ListItemText primary="Shop" onClick={() => setMobileMenuOpen(false)} />
</ListItemButton>
<ListItemButton component={NavLink} to="/about-us" color={isActive('/about-us')}>
<ListItemText primary="About Us" onClick={() => setMobileMenuOpen(false)} />
</ListItemButton>
<ListItemButton component={NavLink} to="/gallery" color={isActive('/gallery')}>
<ListItemText primary="Gallery" onClick={() => setMobileMenuOpen(false)} />
</ListItemButton>
</List>
);

return (
<Toolbar className='header' sx={{ position: 'fixed', top: 0, left: 0, right: 0, zIndex: 1100, backgroundColor: 'white' }}>
<Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', width: '100%' }}>
<IconButton onClick={() => setMobileMenuOpen(true)} sx={{ display: { lg: 'none' } }}>
<MenuIcon />
</IconButton>
<Drawer
anchor="left"
open={mobileMenuOpen}
onClose={() => setMobileMenuOpen(false)}
sx={{
width: 200,
flexShrink: 0,
'&.MuiDrawer-paper': { width: 200, boxSizing: 'border-box' },
display: { lg: 'none', xs: 'block' }
}}
>
{sidebarMenu}
</Drawer>
{
isDesktop &&
<NavLink to="/" style={{ display: 'block' }}>
<img src={`${import.meta.env.VITE_ASSETS_URL}/logo.webp`} alt="logo" style={{ height: '50px', width: 'auto' }} className='logo' />
</NavLink>
}
{
isDesktop &&
<Box sx={{ display: 'flex', justifyContent: 'center', flex: 1 }}>
<Box sx={{ display: 'flex', justifyContent: 'center', gap: 2 }}>
<Button variant='text' component={NavLink} to="/" color={isActive('/') || isActive('/home')} disableRipple
sx={{
'&:hover': {
background: 'none',
color: 'primary.main',
},
'&:active': {
background: 'none',
color: 'primary.main',
},
}}
>Home</Button>
<Button variant='text' component={NavLink} to="/gift-card" color={isActive('/gift-card')} disableRipple
sx={{
'&:hover': {
background: 'none',
color: 'primary.main',
},
'&:active': {
background: 'none',
color: 'primary.main',
},
}}
>Gift Card</Button>
<Button variant='text' component={NavLink} to="/shop" color={isActive('/shop')} disableRipple
sx={{
'&:hover': {
background: 'none',
color: 'primary.main',
},
'&:active': {
background: 'none',
color: 'primary.main',
},
}}
>Shop</Button>
<Button variant='text' component={NavLink} to="/about-us" color={isActive('/about-us')} disableRipple
sx={{
'&:hover': {
background: 'none',
color: 'primary.main',
},
'&:active': {
background: 'none',
color: 'primary.main',
},
}}
>About Us</Button>
<Button variant='text' component={NavLink} to="/gallery" color={isActive('/gallery')} disableRipple
sx={{
'&:hover': {
background: 'none',
color: 'primary.main',
},
'&:active': {
background: 'none',
color: 'primary.main',
},
}}
>Gallery</Button>
</Box>
</Box>
}
<Box>
<IconButton component={NavLink} to='cart' color={isActive('/cart')}>
<Badge badgeContent={totalOrderItems} color="secondary">
<ShoppingBagOutlinedIcon />
</Badge>
</IconButton>
<IconButton component={NavLink} to='profile' color={isActive('/profile')}>
<AccountCircleOutlinedIcon />
</IconButton>
</Box>
</Box>
</Toolbar>
);
}
</code></pre>
<p><strong>Header.css</strong></p>
<pre class="lang-css prettyprint-override"><code>.header {
height: var(--header-height);
overflow: hidden;
box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.1);
}
</code></pre>
 
Top