React

React Create Reusable Animated Sidebar Component Tutorial

The sidebar menu allows you to put essential navigation items in the user’s view. But do you know how to create a sidebar menu component in React?

Well, if your answer is no, then don’t worry.

This detailed tutorial will teach you how to create an animated sidebar menu component in React with a hamburger close and open SVG icon.

To create a reusable sidebar menu module, we will not use any third-party plugin or package. Instead, we will build a full-screen sidebar menu in React from scratch using React hooks (useState, useEffect, useRef).

Hooks will give us cutting-edge solutions to manage the sidebar UI component’s state and other essential behavior.

You can not add the animation, look and feel factor in user interface components without CSS. Hence, to design and add the animation in the react side navbar, we will use the custom CSS that we will write from absolute scratch.

How to Build Animated Sidebar Menu in React with React Hooks

  • Step 1: Create New Project
  • Step 2: Create Component File
  • Step 2: Create Sidebar Menu Component
  • Step 3: Add Custom Styling
  • Step 4: Render Sidebar in View
  • Step 5: Test Sidebar Feature

Create New Project

Not yet created the project, don’t worry here is how you can create your first react project.

On your terminal’s console, add the following command and hit enter. BTW, we assume you have already installed node and npm tools.

npx create-react-app react-proxima

A new blank react app is ready to be developed, just cd into the project.

cd react-proxima

Create Component File

You have to have a separate component file, this is foundation of creating a reusable component in React.

Hence, create components/ directory, inside this directory create SideMenu.js file.

import React from 'react'

export default function SideMenu() {
  return (
    <div>
      <h2>React Reusable Sidebar Menu Example</h2>
    </div>
  )
}

Create Sidebar Menu Component

The component file is ready; first, import the lifecycle hooks.

We need a couple of functions in the function component; these functions will update the state of the component.

We have to close the sidebar when clicking on the body; we need to use the useRef() hook for handling such behavior.

The ref={} attribute keeps the dom element in the .current method. We are using it to close the sidebar when clicked on the body or outside the sidebar element.

import React, { useState, useEffect, useRef } from 'react'

export default function SideMenu() {
  const [isSideMenu, setSideMenu] = useState(false)

  const open = (isSideMenu) => {
    return setSideMenu(!isSideMenu)
  }

  const domeNode = useRef()

  const updateState = (event) => {
    if (domeNode.current.contains(event.target)) {
      return
    }
    setSideMenu(false)
  }

  useEffect(() => {
    document.addEventListener('mousedown', updateState)
    return () => {
      document.removeEventListener('mousedown', updateState)
    }
  }, [])

  return (
    <>
      <header className="topBar">
        <div className="menuBar">
          <span
            ref={domeNode}
            className="navIcon"
            onClick={() => {
              open(isSideMenu)
            }}
          >
            <svg
              xmlns="http://www.w3.org/2000/svg"
              className="h-5 w-5"
              viewBox="0 0 20 20"
              fill="currentColor"
            >
              {isSideMenu ? (
                <path d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" />
              ) : (
                <path d="M3 5a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zM3 10a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zM3 15a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1z" />
              )}
            </svg>
          </span>
        </div>

        <div className="sideMenu" style={{ left: isSideMenu ? '0' : '-265px' }}>
          <a href="#">Menu 01</a>
          <a href="#">Menu 02</a>
          <a href="#">Menu 03</a>
          <a href="#">Menu 04</a>
          <a href="#">Menu 05</a>
          <a href="#">Menu 06</a>
          <a href="#">Menu 07</a>
          <a href="#">Menu 08</a>
          <a href="#">Menu 09</a>
        </div>
      </header>
    </>
  )
}

Add Custom Styling

We are using the custom CSS to add styling in sidebar, you need to open the index.css file. In this file, you require to add the following code.

If you don’t like the aesthetics then you can write your own CSS.

*,
*::before,
*::after {
  padding: 0;
  margin: 0;
  list-style: none;
  box-sizing: border-box;
  list-style-type: none;
}

body {
  font-family: sans-serif;
  font-size: 1.2rem;
  font-weight: normal;
  line-height: 1.6;
  color: #252a32;
  background: rgba(0, 0, 0, 0.1);
}

.topBar {
  height: 5rem;
  display: flex;
  justify-content: center;
  align-content: center;
  background: #110135;
}

.menuBar {
  display: flex;
  align-items: center;
  color: white;
  justify-content: flex-end;
  width: 100%;
}


.navIcon {
  width: 55px;
  display: flex;
  margin-right: 4rem;
  margin-left: 1.5rem;  
  cursor: pointer;
}

.sideMenu {
  left: 0;
  height: 100%;
  width: 260px;
  position: fixed;
  background: rgb(249, 249, 249);
  transition: all 0.35s ease-out;
}

.sideMenu a {
  display: flex;
  align-content: flex-start;
  text-decoration: none;
  font-weight: 600;
  color:rgba(0, 0, 0, 0.8);
  padding: 1rem 1.6rem;
  border-bottom: 1px solid rgba(0, 0, 0, 0.1);
}

.sideMenu a:hover {
  color: rgb(40, 0, 148);
}

Render Sidebar in View

The sidebar component is ready, to utterly run this component in react application. You must need to import and register inside the App.js file.

import React from 'react'
import SideMenu from './components/SideMenu.js'

function App() {
  return (
    <div>
      <SideMenu />
    </div>
  )
}

export default App;

Test Sidebar Feature

Lastly, on your console type the following command and execute the command.

After you run the command, following url appear, use it to check the sidebar.

npm start
http://localhost:3000

Here is the final output, for which we all have been waiting for.

Conclusion

If you have noticed, we used the useRef hook in our functionality.

Generally, the useRef hook returns a mutable ref object; the initial value is passed to the useRef hook. The initial property refers to the DOM element that we are targeting, and it remains in the .current property and is available throughout the component’s lifetime.

We used the useRef hook to track the click on the inside or outside the scope of the component.

We hope that you will be able to build your own custom yet simple hamburger with a sidebar component in React.

Digamber

I am Digamber, a full-stack developer and fitness aficionado. I created this site to bestow my coding experience with newbie programmers. I love to write on JavaScript, ECMAScript, React, Angular, Vue, Laravel.

Recent Posts

How to Add Active Class in Map Items in React Js

In this quick tutorial, we will show you how to quite easily add the active…

1 day ago

How to Create and Use Redux Store in React Js

In this tutorial, we will learn how to create a Redux Store in React application.…

4 days ago

How to Build Dynamic Load More Feature in React Js

This detailed guide will cover how to create the Load More button and display data…

1 week ago

How to Integrate Redux Persist to React Redux Store

In this tutorial, we will step by step learn how to configure redux persist in…

1 week ago

React Redux Save Data in Local Storage with Persist Tutorial

In this comprehensive tutorial, we will learn how to persist redux store's states in React…

2 weeks ago

React Js Tailwind CSS Add Light and Dark Mode Toggler Tutorial

In this guide, we are going to learn how to add dark mode and light…

2 weeks ago