How toReuse route modules in React Router

Sometimes you may need to use the same route module in multiple paths, imagine you're building a modal route, you need this modal route to be on /modal but also on /profile/modal and /settings/modal.

Instead of reexporting the code from multiple files, you can reuse the file in the routes.ts.

app/routes.ts
import { type RouteConfig, route } from "@react-router/dev/routes"; export default [ route("modal", "views/modal.tsx"), route("profile", "views/profile.tsx", [route("modal", "views/modal.tsx")]), route("settings", "views/settings.tsx", [route("modal", "views/modal.tsx")]), ] satisfies RouteConfig;

If we tried to do that it will crash because of the duplicated route id, note that the error happens because of the route id, not the route itself.

The route id by default is generated based on the file path without the file extension, so in the case of the modal it will be views/modal, and it will be the same for every time you use the file.

But luckily for use we can customize it.

app/routes.ts
import { type RouteConfig, route } from "@react-router/dev/routes"; export default [ route("modal", "views/modal.tsx", { id: "modal" }), route("profile", "views/profile.tsx", [ route("modal", "views/modal.tsx", { id: "profile-modal" }), ]), route("settings", "views/settings.tsx", [ route("modal", "views/modal.tsx", { id: "settings-modal" }), ]), ] satisfies RouteConfig;

With this id option we can now reuse the route file in multiple paths.