T
TanStack7mo ago
fair-rose

How To Route Masking Properly With File Based Routing

I tried route masking using file based routes. Here are the routes
// 1st
routes/
├── __root.tsx
├── _pages.tsx
├── _pages.product.index.tsx
├── _pages.product.$productId.tsx
├── _pages.product.$productId.modal.tsx


// 2nd
routes/
├── __root.tsx
├── _pages.tsx
├── _pages.product.index.tsx
├── _pages.product.$productId.tsx
├── _pages.product_.$productId.modal.tsx
// 1st
routes/
├── __root.tsx
├── _pages.tsx
├── _pages.product.index.tsx
├── _pages.product.$productId.tsx
├── _pages.product.$productId.modal.tsx


// 2nd
routes/
├── __root.tsx
├── _pages.tsx
├── _pages.product.index.tsx
├── _pages.product.$productId.tsx
├── _pages.product_.$productId.modal.tsx
The first routes didn't work, The link navigate to the regular product page in /product/$productId. Fortunately the second one is working, modal is open in /product/$productId path, but somehow the products list is gone because it using the modal layout. My expectaction was the modal open but the it stay the same layout where products index _pages.product.index.tsx exist just like the example https://tanstack.com/router/v1/docs/framework/react/examples/location-masking. If it is possible how to do it the right way? By the way i tried both routes with declarative and imperative aproach.
// Link to modal
<Link
to="/shop/$productId/modal"
params={{ productId: product.id }}
>
{product.name}
</Link>

// router.tsx
const productModalToProductMask = createRouteMask({
routeTree,
from: "/shop/$productId/modal",
to: "/shop/$productId",
params: (prev) => ({
productId: prev.productId,
}),
unmaskOnReload: true,
});

export function createRouter() {
const router = createTanStackRouter({
routeTree,
scrollRestoration: true,
routeMasks: [productModalToProductMask],
defaultNotFoundComponent: () => <div>404 Not found</div>,
});
return router;
}

// Link to modal
<Link
to="/shop/$productId/modal"
params={{ productId: product.id }}
>
{product.name}
</Link>

// router.tsx
const productModalToProductMask = createRouteMask({
routeTree,
from: "/shop/$productId/modal",
to: "/shop/$productId",
params: (prev) => ({
productId: prev.productId,
}),
unmaskOnReload: true,
});

export function createRouter() {
const router = createTanStackRouter({
routeTree,
scrollRestoration: true,
routeMasks: [productModalToProductMask],
defaultNotFoundComponent: () => <div>404 Not found</div>,
});
return router;
}

React TanStack Router Location Masking. Example | TanStack Router Docs
An example showing how to implement Location Masking. in React using TanStack Router.
2 Replies
fair-rose
fair-roseOP7mo ago
can't wait for it, thanks for the information

Did you find this page helpful?