How to Create a Responsive Dashboard Sidebar in React JS

How to Create a Responsive Dashboard Sidebar in React JS?

Here are the Steps –

1.  Create Component –

DashSidebar.jsx:

import {Sidebar} from ‘flowbite-react’
import { useEffect, useState } from ‘react’;
import {HiUser, HiArrowSmRight} from ‘react-icons/hi’
import {Link, useLocation} from ‘react-router-dom’
 
const DashSidebar = () => {
    const location=useLocation();
    const [tab, setTab]=useState();
    useEffect(()=>{
        const urlParams=new URLSearchParams(location.search);
        const tabFromUrl=urlParams.get(‘tab’);
        if(tabFromUrl){
            setTab(tabFromUrl)
        }
    },[location.search])
  return (
     <Sidebar className=‘w-full md:w-56’>
        <Sidebar.Items>
            <Sidebar.ItemGroup>
                <Link to=‘/dashboard?tab=profile’>
 
                <Sidebar.Item active={tab===‘profile’} icon={HiUser} labelColor=‘dark’>
                    Profile
                </Sidebar.Item>
                </Link>

                <Sidebar.Item active icon={HiArrowSmRight} className=‘cursor-pointer’>
                    Sign Out
                </Sidebar.Item>

            </Sidebar.ItemGroup>
        </Sidebar.Items>
     </Sidebar>
  )
}
 
export default DashSidebar

2.  Create another Component –

DashProfile.jsx

import React from ‘react’
 
const DashProfile = () => {
  return (
    <div>DashProfile</div>
  )
}
 
export default DashProfile
 

3. Import these components in

Dashboard.jsx –

import { useEffect, useState } from ‘react’;
import {useLocation} from ‘react-router-dom’
import DashSidebar from ‘../components/DashSidebar’;
import DashProfile from ‘../components/DashProfile’;
const Dashboard = () => {
  const location=useLocation();
  const [tab, setTab]=useState();
  useEffect(()=>{
    const urlParams=new URLSearchParams(location.search);
    const tabFromUrl=urlParams.get(‘tab’);
    if(tabFromUrl){
      setTab(tabFromUrl)
    }
  }, [location.search])
  return (
    <div className=‘ min-h-screen flex flex-col md:flex-row’>
    <div className=‘md:w-56’>
    <DashSidebar/>
    </div>
    {
      tab===‘profile’ && <DashProfile/>
    }
    </div>
  )
}
export default Dashboard
 
 
Video Tutorial: