Blog>
Snippets

Initializing TanStack Router with Navigation Blocking

Demonstrate how to set up TanStack Router in a React application and configure navigation blocking to alert users of unsaved changes before navigating away.
import { createBrowserRouter, RouterProvider, useNavigationBlocker } from 'react-router-dom';
Import necessary functions and hooks from 'react-router-dom' to create a router and handle navigation blocking.
function useBlocker(when, message) {
    useNavigationBlocker(when, (tx) => {
        if (window.confirm(message)) tx.retry();
    });
}
Defines a 'useBlocker' hook that uses 'useNavigationBlocker' from TanStack Router (previously react-router-dom) to block navigation. It prompts the user with a confirm dialog using the native 'window.confirm' method.
function BlockerExample() {
    const [isBlocking, setIsBlocking] = React.useState(false);
    // Example toggle function to simulate unsaved changes
    const toggleBlock = () => setIsBlocking(!isBlocking);
    useBlocker(isBlocking, 'You have unsaved changes! Are you sure you want to leave?');
    return (
        <div>
            <p>Blocking: {isBlocking ? 'Yes' : 'No'}</p>
            <button onClick={toggleBlock}>Toggle Blocking</button>
        </div>
    );
}
This component demonstrates using the custom 'useBlocker' hook. It includes a toggle to simulate a change in state that might occur with unsaved form data. When 'isBlocking' is true, navigation away from the page will trigger a confirmation dialog.
const router = createBrowserRouter([
    {
        path: '/',
        element: <BlockerExample/>
    }
]);
Create a TanStack Router router instance with a route configuration. This setup demonstrates a simple route to the 'BlockerExample' component.
function App() {
    return <RouterProvider router={router} />;
}
The main App component that renders the RouterProvider, passing in the router instance. It effectively connects our routing setup to our React application.