Magic Back Button

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

About

The Magic Back button is designed to prevent users from unintentionally leaving your site. When a user directly visits a page with a back button (i.e., their first visit), clicking the button will redirect them to the homepage. However, if they navigate to the page from another part of the site, the button respects the browser's history and behaves like a normal back button, without disrupting the browser's history records.

This component is built on top of React Page Tracker. before using this component, please following the installation.

Try opening this page link in a new tab,
and you’ll notice the button will navigate directly to the homepage. (router.push('/'))
However, if you navigate to this page from another component,
the button will simply go back to the previous page. (router.back())

Installation

1

Install the package if you do not have it.

npx shadcn@latest add button
2

Copy and paste the following code into your project.

import * as React from 'react';
import { cn } from '@/lib/utils';
import { Button, ButtonProps } from '@/components/ui/button';
import { useRouter } from 'next/navigation';
import { usePageTrackerStore } from 'react-page-tracker';
import { ChevronLeft } from 'lucide-react';

export const MagicBackButton = React.forwardRef<
  HTMLButtonElement,
  ButtonProps & { backLink?: string }
>(({ className, onClick, children, backLink = '/', ...props }, ref) => {
  const router = useRouter();
  const isFirstPage = usePageTrackerStore((state) => state.isFirstPage);
  return (
    <Button
      className={cn('rounded-full', className)}
      variant="outline"
      size="icon"
      ref={ref}
      onClick={(e) => {
        if (isFirstPage) {
          router.push(backLink);
        } else {
          router.back();
        }
        onClick?.(e);
      }}
      {...props}
    >
      {children ?? <ChevronLeft />}
    </Button>
  );
});
MagicBackButton.displayName = 'MagicBackButton';
3

npm i react-page-tracker

Following theinstallation to use the package.

Simply import PageTracker in your root layout.

import { PageTracker } from 'react-page-tracker';

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
+        <PageTracker />
        {children}
      </body>
    </html>)
}
4

Update the import paths to match your project setup.

Usage

back to /docs when you first visit this page.

Buy Me A Coffee