Next.js Discord

Discord Forum

How should I refactor that

Unanswered
Rhinelander posted this in #help-forum
Open in Discord
RhinelanderOP
"use client";
export const DashboardNavbar = () => {
  const pathname = usePathname();
  const [breadcrumbs, setBreadcrumbs] = useState<BreadcrumbItem[]>([]);

  useEffect(() => {
    const items = generateBreadcrumbs(pathname);
    setBreadcrumbs(items);
  }, [pathname]);

  return (
    <nav className="flex h-14 flex-row-reverse items-center justify-between gap-x-4 border-b bg-background px-4 py-3 md:flex-row md:justify-start">
      <SidebarTrigger />
      <Separator orientation="vertical" className="hidden md:block" />
      <div className="flex w-full items-center md:w-max">
        {breadcrumbs.length > 1 && (
          <Button variant="ghost" size="icon" asChild className="md:hidden ">
            <Link href={breadcrumbs[breadcrumbs.length - 2].path}>
              <ChevronLeft />
            </Link>
          </Button>
        )}
        <div className="mx-auto max-w-40 truncate pl-4 font-medium text-xl md:hidden">
          {breadcrumbs.length > 0 && breadcrumbs[breadcrumbs.length - 1].label}
        </div>
      </div>
      <div className="hidden md:flex md:items-center md:gap-x-2">
        {breadcrumbs.map((breadcrumb, index) => (
          <div key={breadcrumb.path} className="flex items-center">
            {index > 0 && (
              <ChevronRight className="mx-2 h-4 w-4 text-muted-foreground/50" />
            )}
            <Link
              href={breadcrumb.path}
              className={cn(
                "max-w-40 truncate text-sm",
                index === breadcrumbs.length - 1
                  ? "font-medium"
                  : "text-muted-foreground hover:text-foreground/70"
              )}
            >
              {breadcrumb.label}
            </Link>
          </div>
        ))}
      </div>
    </nav>
  );
};

Goal is to eliminate this state where path and back button are loading. It makes sense for this to "load" as it needs to retrieve the path but just wondering if there is any other way - cleaner code perhaps

1 Reply

American black bear
You don't need to use state here at all:

"use client"

export function Breadcrumbs() {
  const pathname = usePathname()
  const breadcrumbs = generateBreadcrumbs(pathname)

  return <div>{breadcrumbs}</div>
}