T
TanStack3w ago
frozen-sapphire

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 />
}
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 />
}
1 Reply
frozen-sapphire
frozen-sapphireOP3w ago
I'm thinking the best way to do this is to remove all the routes that are not in allowedRoutes, then make them go into ContinueOutside as a not found component, but I'm not sure how to do that Alternatively, I can also define another route tree with code based routing. That's always an option

Did you find this page helpful?