Defining params in React Router v6

Viewed 356

Since the update to React Router v6 the way to render children with params has changed. Previously in v5 you could define expected params in the URL to render a child based on an expected param, but now you can't. Currently updating from v5 to v6 and it's causing issues with routing currently.

I have looked through a few locations in the new documentation, but can't seem to find what I am looking for:

From the documentation:

<Route path="parent" element={<Parent />}>
  <Route path=":child" element={<Child />} />
</Route>

What I am trying to do:

<Route path="parent/:child" element={<Parent />}>
  <Route path="parent/child1" element={<Child1 />} />
  <Route path="parent/child2" element={<Child2 />} />
</Route>

In v5 you could do something where you define the params you expect:

path="parent/:child(child1|child2)"

Is there any way to do this in v6 now? The documents are pretty sparse and not very descriptive. Anyone have a solution to this?

1 Answers

The Route components in RRDv6 don't take REGEX paths anymore. You can read more in depth about that in What Happened to Rexexp Routes Path?

From what I can tell you weren't using the params as variables to access in the routed components, but more for condensed route definitions. In RRDv6 you explicitly render "child1"|"child2" nested route components.

<Route path="parent" element={<Parent />}>
  <Route path="child1" element={<Child1 />} /> // "../parent/child1"
  <Route path="child2" element={<Child2 />} /> // "../parent/child2"
</Route>

Update

It seems you do want to use the child route param to help decide which component to render. For this abstract the params processing into the parent component that conditionally renders the child components.

Example:

const Parent = () => {
  const { child } = useParams();

  switch (child) {
    case "child1":
      return <Child1 />;

    case "child2":
      return <Child2 />;

    default:
      return null;
  }
};

...

<Routes>
  <Route path="parent/:child" element={<Parent />} />
</Routes>

Edit defining-params-in-react-router-v6

Related