How to Create Animated Sidebar Menu in React with React Hooks

Sidebar navigation is the best UI element for showing the navigation items to the users, and it is helpful from ux and ui perspective.

This tutorial will help you find out how to create the animated horizontal sidebar navigation in React application using the React hooks.

We will create the animated sidebar navigation component using the useState, useRef, and useEffect hooks. To add the animation in the sidebar navigation, we will use the CSS3 transition property.

React Js Reusable Animated Sidebar Navigation Component Example

  • Step 1: Install React App
  • Step 2: Build Animated Sidebar Navigation with Hamburger
  • Step 3: Design Sidebar Nav
  • Step 4: Register Component in App Js
  • Step 5: Run Application

Install React App

Let us begin by installing a brand new react app using the given command.

But if you do not want to create a new app and already have an app, jump on to the subsequent step.

npx create-react-app react-sidebar

Move inside the app directory.

cd react-sidebar

Build Animated Sidebar Navigation with Hamburger

Start with creating a new functional component, in this file we will keep the animated side bar component code.

First, create the Components/SidebarNav.js folder and file.

Next, copy and paste the given code into the file.

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

export default function SidebarNav() {
  const [isSidebar, initSidebar] = useState(false)

  const openSidebar = (isSidebar) => {
    // console.log(isSidebar)
    return initSidebar(!isSidebar)
  }

  const node = useRef()

  const trackSidebar = (e) => {
    if (node.current.contains(e.target)) {
      // inside scope click
      return
    }
    // outside scope click
    initSidebar(false)
  }

  useEffect(() => {
    console.log('yo')
    document.addEventListener('mousedown', trackSidebar)
    return () => {
      document.removeEventListener('mousedown', trackSidebar)
    }
  }, [])

  return (
    <>
      <header className="header">
        <nav className="navbar">
          <h2>React Animated Sidebar Example</h2>
          <span
            ref={node}
            className="hamburger"
            onClick={() => {
              openSidebar(isSidebar)
            }}
          >
            <svg
              xmlns="http://www.w3.org/2000/svg"
              className="h-5 w-5"
              viewBox="0 0 20 20"
              fill="currentColor"
            >
              {isSidebar ? (
                <path
                  fillRule="evenodd"
                  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"
                  clipRule="evenodd"
                />
              ) : (
                <path
                  fillRule="evenodd"
                  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"
                  clipRule="evenodd"
                />
              )}
            </svg>
          </span>
        </nav>

        <div
          ref={node}
          className="sidebar-block"
          style={{ left: isSidebar ? '0' : '-260px' }}
        >
          <a href="#">Home</a>
          <a href="#">About</a>
          <a href="#">Products</a>
          <a href="#">Portfolio</a>
          <a href="#">Profile</a>
          <a href="#">Sign out</a>
        </div>
      </header>
    </>
  )
}

The useState hook is being used here to set the initial state; we are manipulating the state using the onClick function and using it to show and hide the sidebar navigation block in react app.

We use the useRef and useEffect hooks to hide the sidebar nav bar when clicking outside the hamburger or close button.

The useRef hook is best for storing the mutable values; ideally, it stores them into the .current property.

We are ordering the react component to take action immediately after the component renders and re-renders.

We are adding the trackSidebar function with mousedown event and cleaning this function before the useEffect runs a new effect.

We added the node variable attached with the useRef hook, also defined the ref into the HTML elements.

Design Sidebar

In this step, you will learn how to design the basic sidebar UI element, we will add the CSS code into the App.css file. Also, we will add the animation in the sidebar navigation by using the transition property.

@charset "UTF-8";
*,
*::before,
*::after {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  list-style: none;
  list-style-type: none;
  text-decoration: none;
  -moz-osx-font-smoothing: grayscale;
  -webkit-font-smoothing: antialiased;
  text-rendering: optimizeLegibility;
}

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

.header {
  display: flex;
  height: 4rem;
  justify-content: center;
  align-content: center;
  border-bottom: 1px solid rgb(227, 227, 227);
  background: #3f51b5;
}

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

h2 {
  display: flex;
  justify-content: flex-end;
  width: 100%;
}

.hamburger {
  width: 40px;
  display: flex;
  cursor: pointer;
  margin-right: 5rem;
  margin-left: 1rem;
}

.sidebar-block {
  position: fixed;
  left: 0;
  height: 100%;
  width: 255px;
  background: white;
  transition: all .35s ease-out;
}

.sidebar-block a {
  display: flex;
  align-content: flex-start;
  text-decoration: none;
  color: rgba(0, 0, 0, 0.9);
  padding: 1rem 1.5rem;
  border-bottom: 1px solid rgba(0, 0, 0, 0.1);
}

.sidebar-block a:hover {
  color: red;
}

Register Component in App Js

Now head over to App.js file, in this file we will have to register the sidebar navigation.

Consequently, import the SidebarNav tag into the file and define inside the return method.

import React from "react";
import './App.css';
import SidebarNav from "./components/SidebarNav";


export default function App() {
  return (
    <SidebarNav />
  );
}

Check React Sidebar in Browser

In the last segment of this guide, we will start the react application. For that, type and invoke the provided command.

npm start

Check the sidebar on the given url.

http://localhost:3000

How to Create Animated Sidebar Menu in React using React Hooks

Summary

We have learned how to build a sidebar navbar component in React app using react hooks throughout this tutorial. We also explained how to use hooks in react functional components.

Additionally, how to set the state using the useState hook, create a DOM reference using the useRef hook, and fire a new event when the component re-renders.