Introduction
In this snippet we will create a simple mobile navigation bar using Chakra UI's drawer component. It will be similar to the one on this website.
Creating the Hamburger Icon Button
To begin, we will create a simple IconButton
to open the Navbar. Declare some basic properties such as aria-label
, m
, and zIndex
.
const Navbar = () => {
return (
<>
<IconButton
pos="fixed"
right={0}
top={0}
m={3}
zIndex="10"
aria-label="Open Menu"
icon={<HamburgerIcon />}
onClick={onOpen} // what's this?
/>
</>
)
}
export default NavBarTop
You will notice that the onClick
property is set to onOpen
. This is from useDisclosure
. Chakra UI gives us this along with isOpen
and onClose
to handle the state of the Drawer.
Adding The Drawer
Import the drawer component and all of its sub components.
import {
useDisclosure,
Drawer,
DrawerOverlay,
DrawerContent,
DrawerHeader,
DrawerBody,
DrawerFooter
} from '@chakra-ui/react'
Now, we can use the Drawer
component to create the drawer. We can add this right under the IconButton
which I will not show below for brevity.
<Drawer onClose={onClose} isOpen={isOpen} size="sm">
<DrawerOverlay />
<DrawerContent>
<DrawerHeader borderBottomWidth="3px">
<Heading>I am the Header!</Heading>
</DrawerHeader>
<DrawerBody>
<Text>I am the body! Add aything in here, even components like Flex and Button.</Text>
<Flex>
<Button />
</Flex>
</DrawerBody>
</DrawerContent>
</Drawer>
The last step is to add the useDisclosure
hook above the return statement.
const { isOpen, onOpen, onClose } = useDisclosure()
More Improvements
Lastly, let's add a button to close the Drawer. We can use the onClose
method to do this. Again, I am not repeating any code for brevity.
<IconButton size="md" onClick={onClose} icon={<CloseIcon fontSize="xs" />} borderRadius={5} />
As always, refer to the Chakra UI docs for additional Drawer props.