React Tutorial- Create Reusable Animated Sidebar Component

React Create Reusable Animated Sidebar Component Tutorial

As we all know very well that the Sidebar Menu always plays an important role since it allows us to put the essential navigation items in the user’s view.

You will be happy to know that creating a sidebar menu component in React is not rocket science. It’s an easy and quick task to execute in the React app.

 

We will be learning 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 be using any third-party plugin or package. But, we will be creating a full-screen sidebar menu in React from scratch using React Hooks (useState, useEffect, useRef).

 

How To Build Animated Sidebar Menu In React With React Hooks

Step 1- Create New React Project

Step 2- Create Component File

Step 3- Create Sidebar Menu Component

Step 4- Add Custom Styling

Step 5- Render Sidebar In View

Step 6- Test Sidebar Feature

 

Let’s learn in detail now:

Step 1- Create New Project

The very first and basic step is just to create a new React project using create-react-app as below.

On our terminal’s console, we simply need to add the following command and hit enter. Do remember that the system should already be having installed node as well npm tools:

npx create-react-app react-proxima

After we have installed the new React app, we need to move into the project directory:

cd react-proxima

 

Step 2- Create Component File

Since we need to have a separate component file, we will be creating components/ directory. Then, SideMenu.js file has to be created inside the directory:

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

 

Step 3- Create Sidebar Menu Component

In this step, we need to import the lifecycle hooks after the component file is ready.

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. Therefore, we require to use the useRef() hook for handling such a 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>
    </>
  )
}

 

Step 4- Add Custom Styling

So, we will use custom CSS for adding the styling in the sidebar. For this, we have to open the index.css file. In this file, we need to just add the given code.

We are also given the option to write our 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);
}

 

Step 5- Render Sidebar In View

So now, our sidebar component is ready. But before, we run this component in our React app, we have 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;

 

Step 6- Test Sidebar Feature

Finally, we have reached the last step of this guide where we just need to type the below command on our console and execute.

When we run the command, we can use it to check the sidebar:

npm start

 

Conclusion

Hope that you have seen the use of useRef() hook in our functionality.

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

In our tutorial, we have used useRef hook to track the client on the inside or outside the scope of the component.

 

When you will follow the above steps for implementing the sidebar component in your React app, you are surely going to find it quite easy.

 

Thanks

Leave a Reply

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