A Guide to Creating a Great Custom Tailwind Sidebar
RonDosh
407 views
14 slides
Mar 15, 2024
Slide 1 of 14
1
2
3
4
5
6
7
8
9
10
11
12
13
14
About This Presentation
We guide you step by step through the process of Tailwind Sidebar navigation and give you all the tools you need to for a responsive sidebar.
Size: 429.25 KB
Language: en
Added: Mar 15, 2024
Slides: 14 pages
Slide Content
A Guide to Creating a Great Custom Tailwind Sidebar
Yash Poojari
CSS SIDEBAR TAILWIND 04 Jan 2024 10 min read
Get ready to learn how to create a dynamic and adaptable tailwind sidebar layout using the
powerful combination of Tailwind CSS and React JS. This article will guide you step by step
through the process of Tailwind Sidebar Navigation, ensuring you have all the tools you need
to build a responsive and customizable sidebar for your web applications. So, let’s dive in and
unlock the potential of these two incredible frameworks!
A sidebar is an essential component in web design that provides easy navigation and
access to important information. In this article, you will learn how to create a sidebar that adapts
to different screen sizes, includes icons for visual representation, supports route highlighting,
and can be customized to match your desired design.
Whether you are a web developer, UI/UX designer, startup founder, freelance coder, or coding
bootcamp student, this tutorial will provide valuable insights. We also provide practical
examples to enhance your skills in creating intuitive and visually appealing sidebars for your
projects. So, let’s dive in and start building our Tailwind CSS sidebar!
What is a Tailwind CSS Sidebar?
Tailwind CSS is a highly customizable utility-first CSS framework allowing developers to build
modern and responsive user interfaces rapidly. It provides a set of pre-defined utility classes
that can be combined to create complex layouts and styles without the need to write custom
CSS.
A sidebar, on the other hand, is a vertical panel we commonly place on the left or right side of a
website layout. It typically contains navigation links, supplementary information, or additional
controls. Sidebars in web design improve user experience by providing easy access to
important sections of a website or application.
When combined with Tailwind CSS, creating a responsive sidebar becomes even easier. With
its extensive set of utility classes and responsive design capabilities, Tailwind CSS allows us to
build sidebars that adapt to different screen sizes, ensuring a seamless experience for users
across devices.
Setting up the Project
To start creating a Tailwind CSS sidebar with React JS, we first need to set up our project
structure. We will use React JS, a framework that provides server-side rendering and other
useful features for building React applications.
In this project, we will be using React Icons to add different icons to our sidebar to improve the
visuals of our design.
First, create a new React JS project and a Components folder by running the following
commands in the terminal:
npx create-react-app my-sidebar-project
cd my-sidebar-project
mkdir components
mkdir components/Layout
Also, we need react-icons installed:
npm install react-icons --save
That’s it; you have successfully set up the project structure for our Tailwind Sidebar Layout.
Now, let’s move on to creating the sidebar component itself.
Creating the Sidebar Component
In this section, we will create the Tailwind CSS sidebar component using functional components
and React Hooks. The Tailwind CSS sidebar component will receive two props: show and setter,
which will control the visibility of the sidebar.
Inside the Layout folder, create a new file called Sidebar.js.
import React from "react";
import { SlHome } from "react-icons/sl";
import { BsInfoSquare, BsEnvelopeAt } from "react-icons/bs";
import { BsCart4 } from "react-icons/bs";
import MenuItem from "./MenuItem";
export default function Sidebar({ show, setter }) {
<div className="flex flex-col">
<MenuItem setter={setter} name="Home" route="/" icon={<SlHome />} />
<MenuItem
setter={setter}
name="Products"
route="/products"
icon={<BsCart4 />}
/>
<MenuItem
setter={setter}
name="About Us"
route="/about"
icon={<BsInfoSquare />}
/>
<MenuItem
setter={setter}
name="Contact"
route="/contact"
icon={<BsEnvelopeAt />}
/>
</div>
</div>
{show ? <ModalOverlay /> : <></>}
</>
);
}
The Sidebar component is a functional component that takes in two props, show and setter.
The show prop controls whether the sidebar is visible or not, while the setter prop is a function
that updates the show prop.
We use uselocation from react-router-dom to get the currently displayed route inside the
Sidebar component. This allows us to highlight the corresponding menu item in the sidebar.
The main structure of the sidebar is wrapped in a div element with a set of Tailwind CSS
classes. The basic styling of the sidebar is defined by the flex bg-blue-800 w-[250px] transition-
[margin-left] ease-in-out duration-500 fixed md:static top-0 bottom-0 left-0 z-40 pr-5 class
combination.
To display the items on the sidebar, we are using MenuItem as a component. We will write this
component in the next section.
To toggle the visibility of the sidebar, we pass the setter function to each MenuItem component
and call it on click. This updates the show prop and triggers a re-render of the Sidebar
component.
Before jumping to the MenuItem component, let’s create a mobile menu for smaller screens.
Implementing the Mobile Menu Bar Component
The mobile menu bar component displays only on smaller screens with limited space. It
provides an alternative way to open and close the sidebar, along with other useful elements
such as a company logo and login button.
Let’s create another file MenuBarMobile.js, inside of the Layout folder.
import React from "react";
import { FiMenu as Icon } from "react-icons/fi";
export default function MenuBarMobile({ setter }) {
return (
<nav className="md:hidden z-20 fixed top-0 left-0 right-0 h-[60px] bg-black flex
[&>*]:my-auto px-2">
<button
className="text-4xl flex text-white"
onClick={() => {
setter((oldVal) => !oldVal);
}}
>
<Icon />
</button>
</nav>
);
}
The MenuBarMobile React component is designed for mobile navigation, featuring a fixed black
bar at the top of the viewport with a menu icon. The navigation bar has a sleek appearance with
a black background and a height of 60 pixels, ensuring a compact layout.
The menu icon, sourced from the react-icons, is styled with a large font size and white text
color. The fixed positioning and z-index of 20 ensure the navigation bar remains visible at the
top of the screen, even during scrolling.
The dynamic functionality is achieved through the setter prop, allowing the menu’s display to be
toggled dynamically when the button is clicked.
This component provides a straightforward and visually appealing mobile navigation solution
focusing on functionality and style.
Now that we have implemented both the Sidebar and MenuBarMobile components let’s move
on to building the Layout component.
Building the Layout Component
The Layout component brings together the Sidebar and MenuBarMobile components, along
with the page’s main content. It also sets a title to the webpage. You can customize the title
further according to the usecase.
Inside the Layout folder, create another file called Layout.js.
import React, { useState } from "react";
import Sidebar from "./Sidebar";
import MenuBarMobile from "./MenuBarMobile";
export default function Layout({ children }) {
const [showSidebar, setShowSidebar] = useState(false);
return (
<>
<title>My Sidebar Project</title>
<div className="min-h-screen">
<div className="flex">
<MenuBarMobile setter={setShowSidebar} />
<Sidebar show={showSidebar} setter={setShowSidebar} />
<div className="flex flex-col flex-grow w-screen md:w-full min-h-screen">
{children}
</div>
</div>
</div>
</>
);
}
The Layout component is defined as a functional component that takes in children as a prop.
Inside the Layout component, we use the useState hook to manage the state of the sidebar
visibility. The showSidebar state variable keeps track of whether the tailwind sidebar is
currently visible or hidden.
The main structure of the layout is wrapped in a div element with a set of Tailwind CSS classes.
The flex class ensures that the layout components are in rows.
Within the layout, we have three sections:
The MenuBarMobile component
The Sidebar component
Placeholder for the main content.
The MenuBarMobile component is placed at the top-left corner of the screen and triggers the
toggleSidebar function in response to user interaction.
The Sidebar component is hidden by default and becomes visible when triggered by user
interaction with the MenuBarMobile component.
The main content is wrapped in a div element with the flex flex-col flex-grow class combination,
ensuring it takes up the remaining space in the layout.
In the next section, we will create the MenuItem component to complete our sidebar and
improve its looks and feel.
Creating the MenuItem Component
We will make the MenuItem component, which we first used in our Sidebar.js file.
Create a file named MenuItem.js and write the following code in it.
import { Link, useLocation } from "react-router-dom";
const MenuItem = ({ icon, name, route, setter }) => {
const router = useLocation();
return (
<Link
to={route}
onClick={() => {
setter((oldVal) => !oldVal);
}}
className={`flex gap-1 [&>*]:my-auto text-md pl-6 py-3 border-b-[1px] border-b-
white/10 ${
router.pathname === route
? "text-white"
: "text-white/50 hover:text-white"
}`}
>
<div className="text-xl flex [&>*]:mx-auto w-[30px]">{icon}</div>
<div>{name}</div>
</Link>
);
};
export default MenuItem;
In this component, we use react-router-dom to check which route we are currently on. This
helps us display the active route to the user so that it is easier for the user to figure out where
they are currently on the website.
The main function of this component is to navigate the user to different pages; for that, we can
utilize Link from react-router-dom to easily and quickly navigate the user to the desired pages.
Making All of it Responsive
The Sidebar component demonstrates a thoughtful approach to responsive design, ensuring an
optimal user experience across various screen sizes. The responsive design elements are
evident in several aspects of the component.
We carefully consider several key factors to ensure the responsiveness of our designs. These
principles are not limited to a specific design; rather, they can be applied universally to all our
creations.
Responsive Principles
Dynamic Width: On larger screens, the sidebar’s width is set to a fixed value of 250 pixels
(w-[250px]). This provides enough space for the menu items and maintains a consistent
layout. However, the width dynamically adjusts on smaller screens to fill the entire screen (w-
screen), accommodating limited space and preventing horizontal overflow.
Transition and Animation: The use of Tailwind CSS classes such as transition-[margin-left]
and ease-in-out duration-500 introduces a smooth transition effect when the sidebar expands
or collapses. This animation enhances the user experience, providing a visually pleasing and
polished interaction.
Conditional Styling for Visibility: The sidebar’s visibility is controlled through conditional
styling. The show prop determines whether the sidebar should be visible or hidden. When
visible (show is true), the sidebar is positioned at the left edge of the screen (ml-0), and when
hidden (show is false), it is positioned off-screen (ml-[-250px]) with a transition to the left edge
on larger screens (md:ml-0).
Modal Overlay for Small Screens: On smaller screens (md:hidden), a modal overlay is
introduced to cover the main content when the sidebar is collapsed. This overlay is semi-
transparent (bg-black/50) and spans the entire screen, clearly indicating that the sidebar is in
focus. Clicking on the overlay triggers the same functionality as clicking on the sidebar,
toggling its visibility.
Fixed and Static Positioning: Fixed positioning ensures that the sidebar remains in view
even when the user scrolls on larger screens. However, on medium-sized screens and above
(md:static), the sidebar becomes part of the normal document flow, adapting to the layout
requirements of different screen sizes.
Example in Action
This is how our Tailwind Sidebar looks like:
To dive deep into responsive design, you can check out the Best Way to Create Responsive
Design.
In responsive designs, breakpoints are an important piece of information that you will be using a
lot; here is a simple table to help you with the concept
Breakpoint Screen Width Range Example Usage
sm 640px and above sm:text-white
md 768px and above md:px-4
lg 1024px and above lg:flex
xl 1280px and above xl:w-½
2xl 1536px and above 2xl:py-8
Supporting Dark Mode
Dark mode has become increasingly popular in modern web design as it reduces eye strain and
improves visibility in low-light environments. In this section, we will demonstrate how to add dark
mode support to our Tailwind CSS sidebar.
Open your project’s main JavaScript file, i.e., app.js, and add the following code:
import '../styles/globals.css';
import { useEffect } from 'react';
function MyApp({ Component, pageProps }) {
useEffect(() => {
const body = document.querySelector('body');
const isDarkMode = localStorage.getItem('darkMode') === 'true';
if (isDarkMode) {
body.classList.add('dark');
}
}, []);
return <Component {...pageProps} />;
}
export default MyApp;
In this code snippet, we import the globals.css file, which contains global CSS styles for our
application. We also use the useEffect hook to apply the dark class to the body element if the
user has enabled dark mode.
Open your project’s styles/globals.css file (create it if it doesn’t exist) and add the following
code:
@tailwind base;
@tailwind components;
.dark {
@apply bg-gray-900 text-white;
}
@tailwind utilities;
In this CSS code snippet, we define the dark class, which sets the background color to dark
gray and the text color to white. This class will be applied to the body element when dark mode
is enabled.
With these changes in place, you can now enable dark mode by adding or removing the “dark”
class from the body element in your JavaScript or TypeScript files. Here’s an example of how to
toggle dark mode using a button:
<button onClick={() => document.querySelector('body').classList.toggle('dark')}>Toggle
Dark Mode</button>
After this, the final output will look something like this:
Congratulations! You have successfully implemented dark mode support for your Tailwind CSS
sidebar.
Here is a video tutorial for Dark Mode functionality.
There are still many things that can be done to improve the user experience based on your
specific use case, one of which can be a Tailwind Sticky Sidebar by using the class sticky.
Summing Up…
In this comprehensive guide, we have covered the process of creating a Tailwind CSS sidebar
with React JS. Following the steps outlined in this tutorial, you have learned how to create a
responsive and customizable sidebar that adapts to different screen sizes, includes icons for
visual representation, supports route highlighting, and even supports dark mode.
We started by setting up the project structure and creating the Sidebar component using
functional components and React Hooks. We then implemented the MenuBarMobile component
to provide a mobile-friendly navigation experience on smaller screens. The Layout component
brought everything together, allowing us to set the page title dynamically.
We integrated popular icon libraries like react-icons to enhance the sidebar and added icons to
our menu items. We also added a collapsible navigation button for smaller screens to ensure a
seamless user experience across devices.
We also demonstrated how Tailwind CSS classes can adjust typography and spacing based on
screen sizes, achieving a fully responsive design.
Finally, we explored how to add dark mode support to our Tailwind CSS sidebar, allowing
users to switch between light and dark themes.
Elevate Your Sidebar Design
We hope this guide has provided valuable insights and practical examples to enhance your
skills in creating intuitive and visually appealing sidebars using Tailwind CSS and Next.js.
Remember, as you continue to develop your projects, feel free to customize and experiment
with different styles and techniques to create unique and engaging user experiences.
Happy coding!
Are you ready to take your web development skills to new heights? If yes, then you should
check PureCode.ai.
PureCode.ai is a developer tool that harnesses AI to transform design images into read-to-use
front-end code. It is also a marketplace that offers over 10000 AI-generated custom components
and allows the application of custom themes on top of Tailwind, MUI, and CSS3. You can check
out PureCode by visiting their website: PureCode.ai.
Share this:
Yash Poojari
More blogs
CSS
Why You Need to Use CSS Minification for Web Performance
01 Mar 2024 12 min read
CSS
Top CSS Shape Generator Tools That Will Make Your Life Easier
26 Feb 2024 12 min read
CSS
Best CSS Background Generator Tools for Stunning Websites
26 Feb 2024 9 min read
Tailwind Blogs
Tailwind Dropdown
Tailwind Cards
Tailwind Config
Tailwind Buttons
Tailwind Breakpoints
Tailwind Grid
MUI Blogs
MUI Typgraphy
MUI Tooltip
MUI Appbar
MUI Stack
MUI Slider
MUI Select
Bootstrap Blogs
Bootstrap vs MUI