Picture of Aravind Ramalingam

Aravind Ramalingam

  • Front-End
  • ChakraUI
  • Navigation Bar
  • Responsive

Create a Responsive Navigation Bar using ChakraUI

Responsive Navigation Bar Cover Image

Introduction

We all know how crucial the navigation bar is for websites. But most websites don't have a good one. Why? Because responsive design for navigation bar is not easy.

How is the navigation bar different?

Usually, when we build a responsive layout using ChakraUI, the common approach is to stack the components horizontally for larger devices & vertically for smaller ones. This approach does not work for navigation bar. A typical navigation bar has the following components:

  • Logo
  • Navigation menu
  • Call-to-action buttons
DesktopMobile
Mobile Navigation BarMobile Navigation Bar Expanded

Based on the device type, we need to rearrange the items. We will see how to build the above navigation bar in 3 steps:

  1. Build desktop version
  2. Build mobile version
  3. Make it responsive

Build desktop version

The desktop version is easy to follow. Wrap all the elements inside a Flex with justify property value as "space-between". To get even spacing between navigation bar items, we will list them inside a HStack component.

Build mobile version

  1. ChakraUI provides the Drawer component, which is a panel that slides out from the edge of the screen. We can place all the navigation items inside the body of the drawer for the mobile version.
  1. We will use the useRef react hook to communicate between the menu icon and drawer. If you don't about this hook or need to refresh your memory then checkout the post React useRef Guide by Dmitri Pavlutin.
  1. Finally, we can add the MobileDrawer component next to the CTA button inside the header.js file.
Navigation MenuNavigation Menu - Expanded
Mobile Navigation BarMobile Navigation Bar Expanded

Make it responsive

DesktopMobile
Desktop Navigation BarMobile Navigation Bar Expanded

All the hard parts are over. Now we just have to hide certain components based on the screen size. Thanks to ChakraUI it's easier than ever by using the display property.

  1. Hide the MobileDrawer component in the Desktop version by adding display={{ base: "flex", md: "none" }} to the Flex component inside it.
  2. Hide the Navigation Items listed inside HStack component in the mobile version by adding display={{ base: "none", md: "flex" }}.

Final Desktop Version:

Desktop Navigation Bar

Final Mobile Version:

Navigation MenuNavigation Menu - Expanded
Mobile Navigation BarMobile Navigation Bar Expanded

Conclusion

Navigation bar is one of those things which look scary to get started, but once you find a good example, it's not that hard to build. Hope you found this post to be useful. For more such posts, follow/DM me via Twitter

Similar article

Create Responsive Cards using ChakraUI