Skip to content

Instantly share code, notes, and snippets.

@pourdaavar
Forked from jaens/storyBookRouter.tsx
Created July 4, 2025 08:03
Show Gist options
  • Save pourdaavar/a46afaec794726844c9611f40f2cf60f to your computer and use it in GitHub Desktop.
Save pourdaavar/a46afaec794726844c9611f40f2cf60f to your computer and use it in GitHub Desktop.

Revisions

  1. @jaens jaens created this gist Feb 18, 2024.
    56 changes: 56 additions & 0 deletions storyBookRouter.tsx
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,56 @@
    /* eslint-disable react-refresh/only-export-components */
    import {
    createMemoryHistory,
    createRootRoute,
    createRoute,
    createRouter,
    useRouterState,
    type NotFoundRouteProps,
    } from "@tanstack/react-router";
    import { createContext, useContext, type ReactNode } from "react";

    //#region Dummy story router
    function RenderStory() {
    const storyFn = useContext(CurrentStoryContext);
    if (!storyFn) {
    throw new Error("Storybook root not found");
    }
    return storyFn();
    }

    export const CurrentStoryContext = createContext<(() => ReactNode) | undefined>(undefined);

    function NotFoundComponent(_props: NotFoundRouteProps) {
    const state = useRouterState();
    return (
    <div>
    <i>Warning:</i> Simulated route not found for path <code>{state.location.href}</code>
    </div>
    );
    }

    const storyPath = "/__story__";
    const storyRoute = createRoute({
    path: storyPath,
    getParentRoute: () => rootRoute,
    component: RenderStory,
    });

    const rootRoute = createRootRoute({
    notFoundComponent: NotFoundComponent,
    });
    rootRoute.addChildren([storyRoute]);

    export const storyRouter = createRouter({
    history: createMemoryHistory({ initialEntries: [storyPath] }),
    routeTree: rootRoute,
    });
    //#endregion

    export function storyRouterDecorator(storyFn: () => ReactNode) {
    return (
    <CurrentStoryContext.Provider value={storyFn}>
    <RouterProvider router={storyRouter} />
    </CurrentStoryContext.Provider>
    );
    }