TanStackT
TanStack6mo ago
1 reply
skinny-azure

Filtered Memory History in Tanstack Router

Heylo, I have a component in my app that renders through a modal which is intended to be a mini-version of the app controlled through memory history. I've achieved this using two RouterProviders using the same route tree.

I'd like to implement a behaviour where if I navigate out of specific routes, it will lead me to a ContinueOutside component, which will have a link to navigate me out (thereby taking me out of the memory history'd router)

I've got a very crude implementation as follows and would like to know if there was a better and typesafe way to do this in Tanstack Router.

If I could also render ContinueOutside within the router provider it would also be a plus.

const router = createRouter({
  routeTree,
  context: {
    // biome-ignore lint/style/noNonNullAssertion: This will be set in React land
    auth: undefined!,
  },
  defaultPreload: 'intent',
  scrollRestoration: true,
  defaultStructuralSharing: true,
  defaultPreloadStaleTime: 0,
  defaultNotFoundComponent: ContinueOutside,
})

const allowedRoutes = ['/clients', '/tasks', '/properties']

const TanstackDrill = () => {
  const { drillUrl } = useContext(SpaContext)
  const auth = useTanstackAuth()

  if (drillUrl === null) return null

  router.history = createMemoryHistory({
    initialEntries: [drillUrl],
  })

  // Only render the RouterProvider if we are in an allowed route
  if (allowedRoutes.some((allowedRoute) => drillUrl.startsWith(allowedRoute))) {
    return <RouterProvider router={router} context={{ auth }} />
  }
  return <ContinueOutside />
}
Was this page helpful?