Back to Articles

Mastering a Dynamic Bootstrap Sidebar: A Step-by-Step Guide

Posted: 3 months agoยทLast Updated: 1 month ago
Blog Cover
Share on LinkedIn
Share on X
Share on Facebook
Share on WhatsApp
Share on Telegram
Share via Email
Copy Link

Creating a responsive and interactive sidebar can significantly enhance the user experience of your web application. In this detailed guide, we'll walk through the implementation of a dynamic Bootstrap sidebar using HTML, CSS, JavaScript, and jQuery. We'll also discuss how this example can be adapted for use with modern technologies like ReactJS.

A sidebar is a crucial element for many web applications, offering easy navigation and access to different sections.

Image

This tutorial will help you build a functional sidebar with Bootstrap that is both elegant and efficient. We'll also explore how to translate this implementation into a ReactJS component for those using modern front-end frameworks.

Our HTML structure is the foundation of the sidebar. We'll include Bootstrap, FontAwesome for icons, and custom CSS for additional styling.

Head Section

The head section includes meta tags for responsiveness and links to Bootstrap, FontAwesome, and custom styles.

<!DOCTYPE html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" />
    <link rel="stylesheet" href="style.css" />
    <link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" />

    <title>Bootstrap Sidebar</title>
  </head>

Body Section

The body section is divided into the sidebar and the main content area. Let's start with the container:

<body>
  <div class="main-container d-flex">
    <div class="sidebar" id="side_nav">
      <!-- Sidebar content here -->
    </div>
    <div class="content">
      <!-- Content here -->
    </div>
  </div>
</body>

Sidebar Content

The sidebar includes a header, a list of navigation items, and additional sections for settings and notifications.

<div class="sidebar" id="side_nav">
  <div class="header-box px-2 pt-3 pb-4 d-flex justify-content-between">
    <h1 class="fs-4">
      <span class="bg-white text-dark rounded shadow px-2 me-2">CL</span>
      <span class="text-white">Coding League</span>
    </h1>
    <button class="btn d-md-none d-block close-btn px-1 py-0 text-white">
      <i class="fal fa-stream"></i>
    </button>
  </div>

  <ul class="list-unstyled px-2">
    <li id="dashboard" class="active">
      <a href="#" class="text-decoration-none px-3 py-2 d-block"><i class="fal fa-home"></i> Dashboard</a>
    </li>
    <li id="projects">
      <a href="#" class="text-decoration-none px-3 py-2 d-block"><i class="fal fa-list"></i> Projects</a>
    </li>
    <li id="messages">
      <a href="#" class="text-decoration-none px-3 py-2 d-block d-flex justify-content-between">
        <span><i class="fal fa-comment"></i> Messages</span>
        <span class="bg-dark rounded-pill text-white py-0 px-2">02</span>
      </a>
    </li>
    <li id="services">
      <a href="#" class="text-decoration-none px-3 py-2 d-block"><i class="fal fa-envelope-open-text"></i> Services</a>
    </li>
    <li id="customers">
      <a href="#" class="text-decoration-none px-3 py-2 d-block"><i class="fal fa-users"></i> Customers</a>
    </li>
  </ul>
  <hr class="h-color mx-2" />
  <ul class="list-unstyled px-2">
    <li id="settings">
      <a href="#" class="text-decoration-none px-3 py-2 d-block"><i class="fal fa-bars"></i> Settings</a>
    </li>
    <li id="notifications">
      <a href="#" class="text-decoration-none px-3 py-2 d-block"><i class="fal fa-bell"></i> Notifications</a>
    </li>
  </ul>
</div>

Main Content Area

The main content area includes a responsive navbar and a dynamic section for displaying content based on the selected sidebar item.

<div class="content">
  <nav class="navbar navbar-expand-md navbar-light bg-light">
    <div class="container-fluid">
      <div class="d-flex justify-content-between d-md-none d-block">
        <button class="btn px-1 py-0 open-btn me-2">
          <i class="fal fa-stream"></i>
        </button>
        <a class="navbar-brand fs-4" href="#"><span class="bg-dark rounded px-2 py-0 text-white">CL</span></a>
      </div>
      <button class="navbar-toggler p-0 border-0" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent">
        <i class="fal fa-bars"></i>
      </button>
      <div class="collapse navbar-collapse justify-content-end" id="navbarSupportedContent">
        <ul class="navbar-nav mb-2 mb-lg-0">
          <li class="nav-item">
            <a class="nav-link active" aria-current="page" href="#">Profile</a>
          </li>
        </ul>
      </div>
    </div>
  </nav>

  <div class="dashboard-content px-3 pt-4" id="content">
    <h2 class="fs-5">Dashboard</h2>
    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Nostrum, totam? Sequi alias eveniet ut quas ullam delectus et quasi incidunt rem deserunt asperiores reiciendis assumenda doloremque provident, dolores aspernatur neque.</p>
  </div>
</div>

JavaScript for Interactivity

To make the sidebar interactive, we'll use jQuery. The script handles the active state of the sidebar items and updates the main content area based on the selected item.

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<script>
  $(".sidebar ul li").on("click", function () {
    $(".sidebar ul li.active").removeClass("active");
    $(this).addClass("active");

    var id = $(this).attr("id");
    var contentTitle, contentText;

    switch (id) {
      case "dashboard":
        contentTitle = "Dashboard";
        contentText = "Lorem ipsum dolor sit amet consectetur adipisicing elit. Nostrum, totam? Sequi alias eveniet ut quas ullam delectus et quasi incidunt rem deserunt asperiores reiciendis assumenda doloremque provident, dolores aspernatur neque.";
        break;
      case "projects":
        contentTitle = "Projects";
        contentText = "Here are the details of your projects. Manage and track the progress of your projects here.";
        break;
      case "messages":
        contentTitle = "Messages";
        contentText = "Check your messages. Stay connected with your team and clients.";
        break;
      case "services":
        contentTitle = "Services";
        contentText = "Explore the services we offer. Enhance your business with our specialized services.";
        break;
      case "customers":
        contentTitle = "Customers";
        contentText = "Manage your customer information and interactions here. Understand and engage with your customers.";
        break;
      case "settings":
        contentTitle = "Settings";
        contentText = "Adjust your preferences and account settings here.";
        break;
      case "notifications":
        contentTitle = "Notifications";
        contentText = "View your notifications and alerts here.";
        break;
      default:
        contentTitle = "Dashboard";
        contentText = "Lorem ipsum dolor sit amet consectetur adipisicing elit. Nostrum, totam? Sequi alias eveniet ut quas ullam delectus et quasi incidunt rem deserunt asperiores reiciendis assumenda doloremque provident, dolores aspernatur neque.";
    }

    $("#content").html(`
      <h2 class="fs-5">${contentTitle}</h2>
      <p>${contentText}</p>
    `);
  });

  $(".open-btn").on("click", function () {
    $(".sidebar").addClass("active");
  });

  $(".close-btn").on("click", function () {
    $(".sidebar").removeClass("active");
  });
</script>

Adapting the Sidebar for ReactJS

For those using modern front-end frameworks like ReactJS, the sidebar can be easily adapted. Here's how you can transform the jQuery-based implementation into a React component.

React Component Structure

We'll create a React component for the sidebar and manage the active state using React's state management.

import React, { useState } from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import '@fortawesome/fontawesome-free/css/all.min.css';

const Sidebar = () => {
  const [activeItem, setActiveItem] = useState('dashboard');
  const [content, setContent] = useState({
    title: 'Dashboard',
    text: 'Lorem ipsum dolor sit amet consectetur adipisicing elit. Nostrum, totam? Sequi alias eveniet ut quas ullam delectus et quasi incidunt rem deserunt asperiores reiciendis assumenda doloremque provident, dolores aspernatur neque.'
  });

  const handleItemClick = (id, title, text) => {
    setActiveItem(id);
    setContent({ title, text });
  };

  return (
    <div className="main-container d-flex">
      <div className="sidebar" id="side_nav">
        <div className="header-box px-2 pt-3 pb-4 d-flex justify-content-between">
          <h1 className="fs-4">
            <span className="bg-white text-dark rounded shadow px-2 me-2">CL</span>
            <span className="text-white">Coding League</span>
          </h1>
          <button className="btn d-md-none d-block close-btn px-1 py-0 text-white">
            <i className="fal fa-stream"></i>
          </button>
        </div>

        <ul className="list-unstyled px-2">
          <li id="dashboard" className={activeItem === 'dashboard' ? 'active' : ''}>
            <a href="#" onClick={() => handleItemClick('dashboard', 'Dashboard', 'Lorem ipsum dolor sit amet consectetur adipisicing elit. Nostrum, totam? Sequi alias eveniet ut quas ullam delectus et quasi incidunt rem deserunt asperiores reiciendis assumenda doloremque provident, dolores aspernatur neque.')} className="text-decoration-none px-3 py-2 d-block"><i className="fal fa-home"></i> Dashboard</a>
          </li>
          <li id="projects" className={activeItem === 'projects' ? 'active' : ''}>
            <a href="#" onClick={() => handleItemClick('projects', 'Projects', 'Here are the details of your projects. Manage and track the progress of your projects here.')} className="text-decoration-none px-3 py-2 d-block"><i className="fal fa-list"></i> Projects</a>
          </li>
          <li id="messages" className={activeItem === 'messages' ? 'active' : ''}>
            <a href="#" onClick={() => handleItemClick('messages', 'Messages', 'Check your messages. Stay connected with your team and clients.')} className="text-decoration-none px-3 py-2 d-block d-flex justify-content-between">
              <span><i className="fal fa-comment"></i> Messages</span>
              <span className="bg-dark rounded-pill text-white py-0 px-2">02</span>
            </a>
          </li>
          <li id="services" className={activeItem === 'services' ? 'active' : ''}>
            <a href="#" onClick={() => handleItemClick('services', 'Services', 'Explore the services we offer. Enhance your business with our specialized services.')} className="text-decoration-none px-3 py-2 d-block"><i className="fal fa-envelope-open-text"></i> Services</a>
          </li>
          <li id="customers" className={activeItem === 'customers' ? 'active' : ''}>
            <a href="#" onClick={() => handleItemClick('customers', 'Customers', 'Manage your customer information and interactions here. Understand and engage with your customers.')} className="text-decoration-none px-3 py-2 d-block"><i className="fal fa-users"></i> Customers</a>
          </li>
        </ul>
        <hr className="h-color mx-2" />
        <ul className="list-unstyled px-2">
          <li id="settings" className={activeItem === 'settings' ? 'active' : ''}>
            <a href="#" onClick={() => handleItemClick('settings', 'Settings', 'Adjust your preferences and account settings here.')} className="text-decoration-none px-3 py-2 d-block"><i className="fal fa-bars"></i> Settings</a>
          </li>
          <li id="notifications" className={activeItem === 'notifications' ? 'active' : ''}>
            <a href="#" onClick={() => handleItemClick('notifications', 'Notifications', 'View your notifications and alerts here.')} className="text-decoration-none px-3 py-2 d-block"><i className="fal fa-bell"></i> Notifications</a>
          </li>
        </ul>
      </div>

      <div className="content">
        <nav className="navbar navbar-expand-md navbar-light bg-light">
          <div className="container-fluid">
            <div className="d-flex justify-content-between d-md-none d-block">
              <button className="btn px-1 py-0 open-btn me-2">
                <i className="fal fa-stream"></i>
              </button>
              <a className="navbar-brand fs-4" href="#"><span className="bg-dark rounded px-2 py-0 text-white">CL</span></a>
            </div>
            <button className="navbar-toggler p-0 border-0" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent">
              <i className="fal fa-bars"></i>
            </button>
            <div className="collapse navbar-collapse justify-content-end" id="navbarSupportedContent">
              <ul className="navbar-nav mb-2 mb-lg-0">
                <li className="nav-item">
                  <a className="nav-link active" aria-current="page" href="#">Profile</a>
                </li>
              </ul>
            </div>
          </div>
        </nav>

        <div className="dashboard-content px-3 pt-4" id="content">
          <h2 className="fs-5">{content.title}</h2>
          <p>{content.text}</p>
        </div>
      </div>
    </div>
  );
};

export default Sidebar;

Explanation

  1. State Management: We use React's useState to manage the active sidebar item and the content displayed.
  2. Event Handling: The handleItemClick function updates the active item and content state.
  3. Conditional Classes: We conditionally apply the active class based on the current state.

CSS for Sidebar

Ensure you include your custom CSS to style the sidebar appropriately.

body {
  background-color: #f8f9fa;
}

.main-container {
  min-height: 100vh;
}

.sidebar {
  min-width: 250px;
  max-width: 250px;
  background-color: #343a40;
  color: #fff;
  transition: all 0.3s;
}

.sidebar.active {
  min-width: 80px;
  max-width: 80px;
}

.sidebar .header-box {
  padding: 15px;
}

.sidebar ul {
  padding: 0;
}

.sidebar ul li {
  padding: 10px;
  list-style: none;
  transition: all 0.3s;
}

.sidebar ul li a {
  color: #fff;
  text-decoration: none;
}

.sidebar ul li.active,
.sidebar ul li:hover {
  background-color: #495057;
}

.content {
  flex: 1;
  padding: 20px;
}

.navbar {
  margin-bottom: 20px;
}

This comprehensive guide has shown you how to create a dynamic Bootstrap sidebar using HTML, CSS, JavaScript, and jQuery. Additionally, I've provided an adaptation for ReactJS, illustrating the flexibility of the implementation. Whether you're using traditional web technologies or modern frameworks, this sidebar can be tailored to fit your needs.

Get the Project's GitHub Link

Happy Coding!

Share on LinkedIn
Share on X
Share on Facebook
Share on WhatsApp
Share on Telegram
Share via Email
Copy Link

Meet Dennis, a seasoned software engineer with 10 years of experience transforming ideas into digital reality. He has successfully guided countless projects from concept to deployment, bringing innovative solutions to life. With a passion for crafting exceptional software, Dennis has helped countless clients achieve their goals.

Click here to learn more

Popular Posts

No popular posts available.

Recommended For You

No related posts found.