Introduction
In responsive websites, we usually see the navigation bar at the top of the page on desktops and a hamburger menu that replaces the navigation bar on mobile screens. A sidebar would appear with the same links as the navigation bar when we press the hamburger menu. In this tutorial, we will look at how to toggle the sidebar with a hamburger menu and a close icon. I am assuming here that you already have a React project set up with a navigation bar and everything, and Tailwindcss installed.
Initial setup
This is what my code looks like in Header.jsx file before I add any code for toggle and sidebar. I only have hamburger menu that does not react on click.
Creating the sidebar
We will be creating the sidebar inside the header.jsx and not as a separate component so that we have everything inside one component and don’t have to manage global variables. The following is the code for the sidebar.
Make sure that the position of the div is set to absolute so that it is outside the normal flow of the document. I have also added md:invisible to make sure that the screen does not show up for screen sizes bigger than 768px.
This is what the whole Header.jsx looks like with the sidebar code in it.
Toggle Implementation
Now we will start implementing the toggle for the sidebar. We will be using useState hook and ternary operators for this.
Start by importing the useState from React.
We will declare a new state variable, which we will call isOpen and set the initial state to false.
Now, we need a ternary operator to make the sidebar come out. The logic is this. I will have a condition and if the condition is true, the first expression is shown and if the condition is false, the second expression is shown. So here, for condition, it will be isOpen. I am going to take the boolean value from the state variable itself. If the isOpen is true, that means the side bar is open and the sidebar div should be shown, so I will add the sidebar div as the first expression. We will start the code under the original navigation bar.
Ternary operator logic
isOpen? <div of sidebar>:<hamburger menu button>
Now we need an onClick event on the hamburger menu and close button to toggle the sidebar to come out and close.
We will now add the function for the onClick event underneath the useState hook. The function is a ternary operator and it will look at the state variable “isOpen” for true or false. The condition is checking if “isOpen” is equal to true. If “isOpen” is equal to true, then the condition is true and it will be set isOpen to false. If the condition is false, which means “isOpen” is not equal to true, it will be set to true.
If isOpen is false, the screen will just show the hamburger menu button. When we click on the hamburger menu button, the onclick will trigger the function Toggleside and cause isOpen to become true. This will then open the sidebar.