A Central Sidebar Menu Configuration

darkterminal avatar
GitHub Account@darkterminal
LanguageJAVASCRIPT
Published At2023-05-27 13:06:56

The Backstory about your JavaScript Metaphor

As I embarked upon the realm of crafting a Next.js project infused with TypeScript, I encountered a profound necessity—a central sidebar menu configuration that would bestow upon us a realm of consistency and scalability. Our noble objective was to fashion a malleable menu system, one that could gracefully accommodate updates and bespoke alterations across an array of pages and components. With TypeScript as our steadfast companion, we sought to harness its formidable power of static typing, thereby fortifying our code with unwavering reliability and unwaning maintainability. Armed with meticulous planning and ingenious design, we embarked upon a grand odyssey—a quest to forge a central sidebar menu configuration, an embodiment of harmonized navigation, and a guarantee of a sublime user experience throughout our illustrious endeavor.

The JavaScript Story!

As we are well aware, when treading the realms of TypeScript, it is incumbent upon us to fashion meticulous definitions. These exquisite artifacts bestow upon us the power to discern errors swiftly during the development process and promptly rectify them.

I am embarking on a project utilizing Next.js App Router and Shadcn-UI. This endeavor marks a new and momentous chapter in my career as a Software Freestyle Engineer.

The Abstract Definition

In the vein of crafting a research journal, I am compelled to fashion an abstract that shall subsequently unfold into a captivating phenomenon of eloquent prose, adorned with a hint of narcissistic flair.

1// Filename: types/sidebar.ts
2export interface SubmenuItems {
3    label: string;
4    link: string;
5}
6
7export interface NavItems {
8    label: string;
9    icon: React.ReactElement | undefined;
10    link: string;
11    isParent: boolean;
12    subMenu?: SubmenuItems[];
13}
14
15export interface SidebarProps extends React.HTMLAttributes<HTMLDivElement> {
16    menus: NavItems[];
17}

The following code presents a comprehensive definition of TypeScript interfaces and React component prop types for a sidebar component.

  • The SubmenuItems interface delineates the composition of submenu items within the sidebar. It encompasses two properties: label, denoting the label for the submenu item, and link, representing the associated URL link.

  • The NavItems interface outlines the structure of navigation items within the sidebar. It encompasses properties such as label for the navigation item label, icon for the corresponding React element depicting the item's icon, link for the associated URL link, isParent to indicate the presence of submenus, and an optional subMenu property of type SubmenuItems[], which facilitates the definition of an array of submenu items.

  • The SidebarProps interface extends the HTML attributes of a div element and introduces a menus property of type NavItems[]. This property allows for the definition of an array of navigation items to be passed as props to the sidebar component.

In essence, this code provides a structured approach to defining types and props required for a sidebar component, promoting seamless utilization and type-checking within a React application.

A Central Sidebar Configuration

A well-designed sidebar menu like this one is a testament to the power of intuitive UI/UX, providing users with a clear and structured path to navigate through various sections of an application

1// Filename: config/sideMenu.tsx
2import { NavItems } from "@/types/sidebar";
3import { Icons } from "@/components/icons";
4
5export const sideMenu: NavItems[] = [
6  {
7    label: "Master Data",
8    icon: undefined,
9    link: "javascript:;",
10    isParent: false,
11  },
12  {
13    label: "Master Korcam",
14    icon: <Icons.userSquare className="w-4 h-4" />,
15    link: "/dashboard/master-korcam",
16    isParent: false,
17  },
18  {
19    label: "Master Kordes",
20    icon: <Icons.userSquare className="w-4 h-4" />,
21    link: "/dashboard/master-kordes",
22    isParent: false,
23  },
24  {
25    label: "Master Korlap",
26    icon: <Icons.userSquare className="w-4 h-4" />,
27    link: "/dashboard/master-korlap",
28    isParent: false,
29  },
30  {
31    label: "Master Pemilih",
32    icon: <Icons.userSquare className="w-4 h-4" />,
33    link: "/dashboard/master-pemilih",
34    isParent: false,
35  },
36  {
37    label: "Settings",
38    icon: <Icons.settings className="w-4 h-4" />,
39    link: "/settings",
40    isParent: true,
41    subMenu: [
42      {
43        label: "Profile",
44        link: "/settings/profile",
45      },
46      {
47        label: "Preferences",
48        link: "/settings/preferences",
49      },
50    ],
51  },
52]

The provided code establishes an arrangement for the sidebar navigation menu within a dashboard or application through the definition of an array named sideMenu, having a type of NavItems[].

Each element within the sideMenu array represents a distinct menu item within the sidebar. These elements possess properties such as label for the menu item's label, icon for associating an icon with the menu item (utilizing the Icons component), link for the corresponding URL link, and isParent to signify whether the menu item contains submenus.

The code initializes the sideMenu array with various menu items. For instance, "Master Data" serves as a top-level item without an icon. Additionally, other items such as "Master Korcam," "Master Kordes," and so forth, are equipped with icons sourced from the Icons component, along with their respective links.

Furthermore, there exists a "Settings" menu item adorned with the "settings" icon, and isParent is set to true, indicating the presence of submenus. The submenus themselves are defined within the subMenu property as an array of objects comprising label and link properties.

All in all, this code establishes the configuration for a sidebar menu, encompassing an array of menu items complete with labels, icons, links, and submenus. This configuration can be employed to render the sidebar navigation within a React application.

The Sidebar Component

Once we have abstracted our imagination and begun unraveling it into a journey towards the dream we desire—an exquisite center of command for the sidebar menu in our application—it is now time to execute our intentions and bring forth the creation of the sidebar menu component.

1// Filename: components/sidebar.tsx
2"use client"
3
4import Link from "next/link"
5import { usePathname } from "next/navigation"
6
7import {
8  Accordion,
9  AccordionContent,
10  AccordionItem,
11  AccordionTrigger,
12} from "@/components/ui/accordion"
13import { Button, buttonVariants } from "@/components/ui/button"
14import { ScrollArea } from "@/components/ui/scroll-area"
15import { cn } from "@/lib/utils"
16import { SidebarProps } from "@/types/sidebar"
17
18import { Icons } from "./icons"
19
20export function Sidebar({ className, menus }: SidebarProps) {
21  const pathname = usePathname()
22  return (
23    <div className={cn("pb-12", className)}>
24      <div className="space-y-4 pb-2">
25        <div className="py-2">
26          <ScrollArea className="min-h-[300px] max-h-screen px-2">
27            <div className="space-y-1 p-2">
28              <Link
29                className={`${buttonVariants({
30                  size: "sm",
31                  variant: pathname === "/dashboard" ? "default" : "ghost",
32                  align: "flexLeft",
33                })}`}
34                href={"/dashboard"}
35              >
36                <span className="inline-flex items-center justify-center gap-1">
37                  <Icons.home className="w-4 h-4" /> Dashboard
38                </span>
39              </Link>
40              {menus?.map((menu, i) => {
41                if (menu.isParent === false && menu.link === "javascript:;" && menu.icon === undefined) {
42                  return <strong key={`${menu}-${i}`} className="font-bold inline-flex items-start justify-start text-xs text-gray-700 dark:text-gray-400">{menu.label}</strong>
43                } else if (menu.isParent && menu.link !== "javascript::" && menu.icon !== undefined) {
44                  return (
45                    <Accordion
46                      key={`${menu}-${i}`}
47                      type="single"
48                      collapsible
49                      className="w-full"
50                    >
51                      <AccordionItem value={`item-${i}`} className="border-b-0">
52                        <AccordionTrigger
53                          className={buttonVariants({
54                            size: "sm",
55                            variant:
56                              pathname === menu.link ? "default" : "ghost",
57                            align: "flexBetween",
58                            className: "hover:no-underline",
59                          })}
60                        >
61                          <span className="inline-flex items-center justify-center gap-1">
62                            {menu.icon} {menu.label}
63                          </span>
64                        </AccordionTrigger>
65                        <AccordionContent>
66                          {menu.subMenu?.map((subItem, subIndex) => (
67                            <Button
68                              key={`${subIndex}-${i}`}
69                              variant="ghost"
70                              size="sm"
71                              className="w-full justify-start font-normal"
72                            >
73                              &mdash; {subItem.label}
74                            </Button>
75                          ))}
76                        </AccordionContent>
77                      </AccordionItem>
78                    </Accordion>
79                  )
80                } else {
81                  return (
82                    <Link
83                      key={`${menu}-${i}`}
84                      className={`${buttonVariants({
85                        size: "sm",
86                        variant: pathname === menu.link ? "default" : "ghost",
87                        align: "flexLeft",
88                      })}`}
89                      href={menu.link}
90                    >
91                      <span className="inline-flex items-center justify-center gap-1">
92                        {menu.icon} {menu.label}
93                      </span>
94                    </Link>
95                  )
96                }
97              })}
98            </div>
99          </ScrollArea>
100        </div>
101      </div>
102    </div>
103  )
104}

The sidebar menu component will dynamically process and categorize the menus defined in config/sideMenu.tsx. Isn't this truly impressive? We simply need to define the menus we wish to display on the sidebar within a single configuration file.

Here is an illustration showcasing the transformation from the realm of imagination to the realization of our previous endeavors.

[Imagine -> Plan -> Create -> Achieve]

  1. Imagination: Visualizing the concept of a dynamic sidebar menu configuration.
  2. Planning: Mapping out the structure and properties of the menu items.
  3. Creation: Implementing the code to define the menu items and their characteristics.
  4. Achievement: Witnessing the manifestation of our vision as the dynamic sidebar menu comes to life.

This journey exemplifies the power of imagination and execution in bringing ideas to fruition.

[The Graph - 001] - Sidebar Menu Title & Sidebar Menu Items

Graph - 001

[The Graph - 002] - Nested Menu in Sidebar Navigation

Graph - 002

The Live Version of Our Imagination

Peek 2023-05-27 17-52

The Last Freestyle Improvisation

As is my custom, I always strive to innovate upon existing foundations while staying true to my own character as a Software Freestyle Engineer.

The default button component provided by Shadcn-UI may not fully satisfy the imaginative requirements we envision. However, with a few modifications, we can transform it into something truly remarkable.

1// Filename: components/ui/button.tsx
2import * as React from "react"
3import { VariantProps, cva } from "class-variance-authority"
4
5import { cn } from "@/lib/utils"
6
7const buttonVariants = cva(
8  "rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:opacity-50 disabled:pointer-events-none ring-offset-background",
9  {
10    variants: {
11      variant: {
12        default: "bg-primary text-primary-foreground hover:bg-primary/90",
13        destructive:
14          "bg-destructive text-destructive-foreground hover:bg-destructive/90",
15        outline:
16          "border border-input hover:bg-accent hover:text-accent-foreground",
17        secondary:
18          "bg-secondary text-secondary-foreground hover:bg-secondary/80",
19        ghost: "hover:bg-accent hover:text-accent-foreground",
20        link: "underline-offset-4 hover:underline text-primary",
21      },
22      size: {
23        default: "h-10 py-2 px-4",
24        sm: "h-9 py-1.5 px-3 rounded-md",
25        lg: "h-11 px-8 rounded-md",
26      },
27      align: {
28        flexLeft: 'flex items-start justify-start',
29        flexCenter: 'flex items-center justify-center',
30        flexRight: 'flex items-end justify-end',
31        flexBetween: 'flex items-center justify-between',
32        inlineLeft: 'inline-flex items-start justify-start',
33        inlineCenter: 'inline-flex items-center justify-center',
34        inlineRight: 'inline-flex items-end justify-end',
35        inlineBetween: 'inline-flex items-center justify-between'
36      },
37    },
38    defaultVariants: {
39      variant: "default",
40      size: "default",
41      align: 'flexCenter'
42    },
43  }
44)
45
46export interface ButtonProps
47  extends React.ButtonHTMLAttributes<HTMLButtonElement>,
48    VariantProps<typeof buttonVariants> {}
49
50const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
51  ({ className, variant, size, ...props }, ref) => {
52    return (
53      <button
54        className={cn(buttonVariants({ variant, size, className }))}
55        ref={ref}
56        {...props}
57      />
58    )
59  }
60)
61Button.displayName = "Button"
62
63export { Button, buttonVariants }

And I awoke from a profoundly beautiful dream, only to discover that the dream had indeed become a reality.

A JavaScript demo/repos link

No response

PayPal Link for Donation (JavaScript Storyteller)

No response

Share This Story