Blog>
Snippets

Custom Block Prompts for Enhanced User Experience

Explain how to create custom block prompts using TanStack Router's blocking features, enhancing user experience with stylized modals or custom messages when navigation is blocked.
import { useEffect } from 'react';
import { useBlocker } from '@tanstack/react-location';
Imports the necessary hooks from React and TanStack Router for blocking navigation.
const CustomBlockPrompt = ({ when, message }) => {
  useBlocker((tx) => {
    if (!window.confirm(message)) {
      tx.abort();
    }
  }, when);

  return null;
};
Defines a `CustomBlockPrompt` component that uses `useBlocker` to conditionally block navigation based on the `when` argument. It displays a browser confirm dialog with the provided `message` as a simple example of customization.
const App = () => {
  return (
    <div>
      <CustomBlockPrompt
        when={true}
        message={'Are you sure you want to leave this page?'}
      />
      {/* Your app components here */}
    </div>
  );
};
Sets up the `App` component to include the `CustomBlockPrompt`, demonstrating its usage. It will prompt the user with a message when they attempt to navigate away from the current page.