UsePageLeaveDemo
guarahooks/use-page-leave-demoFreeExample
use-page-leave's hook in action.
Install it
npx shadcn@latest add https://guarahooks.com/r/use-page-leave-demo.jsonSource
1'use client';23import React, { useEffect } from 'react';45import { Badge } from '@/components/ui/badge';6import { Button } from '@/components/ui/button';7import {8 Card,9 CardContent,10 CardDescription,11 CardFooter,12 CardHeader,13 CardTitle,14} from '@/components/ui/card';1516import { cn } from '@/lib/utils';1718import { usePageLeave } from '@/hooks/guarahooks/use-page-leave';1920export default function UsePageLeaveDemo() {21 const { isPageLeft, onPageLeave } = usePageLeave({22 showConfirmation: true,23 confirmationMessage:24 'Are you sure you want to leave? Unsaved changes may be lost.',25 });2627 useEffect(() => {28 onPageLeave(() => {29 // Custom action when the user leaves the page (tab switch)30 // Example: save draft, send telemetry, etc.31 // Replace this with whatever logic you need32 // eslint-disable-next-line no-console33 console.log('User left the page (tab switch)');34 });35 }, [onPageLeave]);3637 return (38 <Card className="relative max-w-sm w-full">39 <CardHeader>40 <CardTitle>usePageLeave</CardTitle>41 <CardDescription>42 This component demonstrates the <code>usePageLeave</code> hook to43 detect when the user switches tabs or tries to leave the page.44 </CardDescription>45 </CardHeader>46 <CardContent className="space-y-4">47 <Badge48 variant="secondary"49 className={cn(50 'w-fit',51 isPageLeft52 ? 'bg-yellow-500/30 border-yellow-500 text-yellow-700'53 : 'bg-green-500/30 border-green-500 text-green-700',54 )}55 >56 {isPageLeft57 ? 'You left the page (tab in background)'58 : 'You are viewing this page'}59 </Badge>60 <p className="text-sm text-muted-foreground">61 Open another tab or minimize the browser to see the status change.62 <br />63 Also try closing or reloading the page to see the confirmation alert.64 </p>65 </CardContent>66 <CardFooter>67 <Button68 size="sm"69 variant="outline"70 onClick={() => window.location.reload()}71 >72 Reload page73 </Button>74 </CardFooter>75 </Card>76 );77}
What it pulls in
Other registry items
Files it writes
More from guarahooks
All 100 items| Component | Registry | Kind | Access | Installs | Command |
|---|---|---|---|---|---|
| UseAbortControllerDemouse-abort-controller-demo | guarahooks | Examples | Free | no deps | |
| UseArrayStateDemouse-array-state-demo | guarahooks | Examples | Free | no deps | |
| UseAxiosDemouse-axios-demo | guarahooks | Examples | Free | no deps | |
| UseBatteryStatusDemouse-battery-status-demo | guarahooks | Examples | Free | no deps | |
| UseBetterAuthDemouse-better-auth-demo | guarahooks | Examples | Free | no deps | |
| UseClickOutsideDemouse-click-outside-demo | guarahooks | Examples | Free | no deps | |
| UseConfirmDemouse-confirm-demo | guarahooks | Examples | Free | no deps | |
| UseCookieDemouse-cookie-demo | guarahooks | Examples | Free | no deps |
