javascriptreactjsreact-router

How to make a nested route the site index route in React-Router v7


Here is an example routes.tsx file for my React-Router v7 application

import {
  type RouteConfig,
  index,
  prefix,
  route
} from "@react-router/dev/routes";

export default [
  index ("pages/main-site/home/welcome.tsx"),

  // Main Site
  route ("home", "pages/main-site/home.tsx", [
    route("welcome", "pages/main-site/home/welcome.tsx"),
    route("events", "pages/main-site/home/events.tsx"),
    route("contact", "pages/main-site/home/contact.tsx"),
    route("about", "pages/main-site/home/about.tsx"),
  ]),

] satisfies RouteConfig;

The nested route for my welcome page is the module that I want as the default for the whole site. In other words I want the path "/" to redirect to "/home/welcome".

The current file has a couple problems:

  1. React-Router complains that the index route is duplicated with the nested route in the Main Site tree.
  2. If the site does open the index as written, it doesn't see it as a child of home.tsx, so the page elements of home.tsx do not get rendered.

If I remove the root index entry, everything works as defined, but the path for "/" is now undefined and leads nowhere.

How can I make "/" and "home/welcome" both work?


Solution

  • Actually, the new page in react-router-v7 should be:

    import { redirect } from "react-router";
    import type { Route } from "./+types/default-home";
    
    export async function clientLoader({ request }: Route.ClientActionArgs) {
      return redirect("/home/welcome");
    };
    
    export default function DefaultHome() {
        return (
            <>
            </>
        )
    }
    

    and the routes.tsx file should be:

    import { type RouteConfig, index, route } from "@react-router/dev/routes";
    
    export default [
      // Loader redirects from `"/"` to `"/home/welcome"`
      index("pages/main-site/default-home.tsx"),
    
      // Main Site
      route("home", "pages/main-site/home.tsx", [
        route("welcome", "pages/main-site/home/welcome.tsx"),
        route("events", "pages/main-site/home/events.tsx"),
        route("contact", "pages/main-site/home/contact.tsx"),
        route("about", "pages/main-site/home/about.tsx"),
      ]),
    ] satisfies RouteConfig;