Create A Hamburger Menu Using Chakra-UI — A Practical Example Of JavaScript’s useState

Read this post with code syntax highlighting on


If you are familiar with Bootstrap, you know how easy it is to create a responsive nav-bar. In Chakra-UI, there is no built in, out of the box solution. In this post, we will create a responsive nav-bar component that you can use in your React app.

Feel free to check out my video version of this article.

The Idea

We will create 2 nav bars and use useState to dynamically change the css display property to hide and show the nav bar on desktop and mobile.


We will be using Next.js in this example but it works for any react based framework. Navigate to the Next.js GitHub repo and clone their starter example using Chakra-UI. If you don’t want to leave this page the command is yarn create next-app — example with-chakra-ui with-chakra-ui-app.

Open this in your preferred IDE — mine is VSCode. Inside of src/components, open up the `DarkModeSwitch` component. This is the only file we will be modifying.

We will start by importing everything we need.

First, wrap everything inside of a Flex element. Then, add the below code.

This is simply our desktop nav bar. We will add the mobile content below the comment mobile content. Let’s do that now.

Using useState To Open And Close Navigation

Now that we have content, we need a way to show it. We can use `useState` for this. Before the return statement, add the following line:

const [display, changeDisplay] = useState(‘none’)

We now have a variable display set initially to none, and a method changeDisplay we can use to change it (changing the state).

Let’s add this to our code. Note, I am only writing the components that we are changing below.

Now we should be able to open and close the menu! It looks a bit messy though. Let’s add styles to the Flex.

The important styles we added:

  • Setting the height to 100vh
  • Setting the width to 100vw
  • Setting the position to fixed
  • Making z-index 20 so it is above the page content
  • Setting top and left to 0
  • Setting the display to our dynamic display variable.

The rest of the added styles are subjective.

Completed Code

And that’s it! Here is the completed code:

I encourage you to play around with this and change the look and feel. Maybe make it a dropdown instead of filling the whole page, or use framer-motion to add some animation. If you liked this article feel free to check out my YouTube channel where I post a bunch of programming tutorials!

Developer, creator, writer, and student living and working in CT.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store