chakra-ui.png

Chakra-UI Mobile Navbar (Drawer Component)

Use Chakra UI's drawer component to create a simple mobile navigation bar.

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.

1

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.

2

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();
3

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.


Published on August 02, 2021 (2 months ago) in

#chakra-ui

View Related Posts

  • Advanced Chakra UI

    chakra-ui
  • Chakra-UI Responsive Navigation Bar

    chakra-ui

Was this snippet helpful?


Written By Benjamin Carlson

Founder coffeeclass.io

More Articles By Benjamin Carlson


Legal

Terms

Disclaimer

Privacy Policy

Carlson Technologies Logo© Copyright 2021, Carlson Technologies LLC. All Rights Reserved.

Powered by

Vercel Logo