shadcn-expansions
Navigation
UI
Utils

magic-back-button

Redirects first-time visitors to the homepage; otherwise, respects browser history.

navigation
button
back
history
View Docs

Source Code

Files
magic-back-button.tsx
1"use client";
2import { Button, type ButtonProps } from "@/components/ui/button";
3import { cn } from "@/lib/utils";
4import { ChevronLeft } from "lucide-react";
5import { useRouter } from "next/navigation";
6import * as React from "react";
7import { usePageTrackerStore } from "react-page-tracker";
8
9export const MagicBackButton = React.forwardRef<
10  HTMLButtonElement,
11  ButtonProps & { backLink?: string }
12>(({ className, onClick, children, backLink = "/", ...props }, ref) => {
13  const router = useRouter();
14  const isFirstPage = usePageTrackerStore((state) => state.isFirstPage);
15  return (
16    <Button
17      className={cn("rounded-full", className)}
18      variant="outline"
19      size="icon"
20      ref={ref}
21      onClick={(e) => {
22        if (isFirstPage) {
23          router.push(backLink);
24        } else {
25          router.back();
26        }
27        onClick?.(e);
28      }}
29      {...props}
30    >
31      {children ?? <ChevronLeft />}
32    </Button>
33  );
34});
35MagicBackButton.displayName = "MagicBackButton";
36