How to toggle the sidebar with an icon in React

In this article, we will show you how to toggle the sidebar component using Hooks in React. You may need to create a structure for your React application where you have to toggle the sidebar element by clicking the hamburger button from the header.

So in this example, we will add a sidebar component that will be toggled by clicking on the header button. We will only display Icons in the sidebar when it is in minimized mode.

Demo Application

Output - How to toggle the sidebar with an icon in React - Clue Mediator
Output – How to toggle the sidebar with an icon in React – Clue Mediator

How to toggle the sidebar with an icon in React

  1. Project structure
  2. Package dependencies
  3. Create HTML structure
  4. Add CSS
  5. Output

1. Project structure

Refer to the following project structure to toggle the sidebar component in React application.

  • react-toggle-sidebar
    • node_modules
    • public
      • index.html
    • src
      • App.js
      • index.css
      • index.js
    • package-lock.json
    • package.json
    • README.md

2. Package dependencies

In this example, we have to install the bootstrap and bootstrap-icons npm packages. Run the following command to install the npm packages.

You will find the version of following packages in React application.

react
^18.1.0
bootstrap
^5.2.3
bootstrap-icons
^1.10.3

3. Create HTML structure

First, let’s create a HTML design with toggle the sidebar functionality. Here, we will use the useState to toggle the sidebar component.

App.js

In the above code, you will see that we have imported the bootstrap and bootstrap-icons to load the CSS.

4. Add CSS

Now, we have to add the style in the index.css file to design the sidebar component. We will also add the stye for responsive structure.

index.css

5. Output

Run the application and check the output in the browser.

I hope you find this article helpful.
Thank you for reading. Happy Coding..!! 🙂

Demo & Source Code

GitHub Repository StackBlitz Project
If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *