T8 React Router

Middleware

Routing middleware are optional actions to be done before and after a SPA navigation occurs.

The code below shows some common examples of what can be handled with routing middleware: redirecting to another route, preventing navigation with unsaved user input, setting the page title based on the current URL.

import { useNavigationComplete, useNavigationStart } from "@t8/react-router";

function setTitle({ href }) {
  document.title = href === "/intro" ? "Intro" : "App";
}

let App = () => {
  let { route } = useRoute();
  let [hasUnsavedChanges, setUnsavedChanges] = useState(false);

  let handleNavigationStart = useCallback(({ href }) => {
    if (hasUnsavedChanges) return false; // prevents navigation

    if (href === "/intro") {
      route.assign("/"); // redirects
      return false;
    }
  }, [hasUnsavedChanges, route]);

  useNavigationStart(handleNavigationStart);
  useNavigationComplete(setTitle);

  // ...
};

⬥ The object passed to the middleware callback contains href and referrer, the navigation destination and initial URLs. The rest of the properties are aligned with the link data-* props, with the data- prefix stripped from the props' names.

⬥ The callback of both hooks is first called when the component gets mounted if the route is already in the navigation-complete state.

⬥ The optional callback parameter of useRoute(callback?) can be used as middleware defining actions to be taken right before or after components get notified to re-render in response to a URL change. This callback receives the render function as a parameter that should be called at some point. Use cases for this callback include, for example, activating animated view transitions or (less likely in regular circumstances) skipping re-renders for certain URL changes.