skip to Main Content

How to make an endless route?

I have an unknown nesting, following which we need to display it in the route, for example

Folder url.com/folder
-Child 1 url.com/folder/child1
--Child 2 url.com/folder/child1/child2
---Child 3 url.com/folder/child1/child2/child3
---- Child 4 url.com/folder/child1/child2/child3/child4
...

<Route path="folder">
  <ComponentExample />
</Route>

How to determine the route if the nesting is unknown?

2

Answers


  1. Use the current segment, e.g. "directory", followed by the "*" wildcard character to indicate that anything after the segment can also be matched.

    const RootComponent = {
      ...
    
      return (
        <Routes>
          ...
          <Route path="/folder/*" element={<ComponentExample />} />
          ...
        </Routes>
      );
    };
    

    This routed component then renders descendent routes relative to this parent path.

    const ComponentExample = () => {
      ...
    
      return (
        <Routes>
          ...
          <Route path="child1/*" element={<Child1 />} /> // <-- "/folder/child1/*
          ...
        </Routes>
      );
    };
    

    And so on until you finally reach a leaf node that doesn’t render another set of descendent routes.

    If you just intend to render this same ComponentExample for any "/folder/* then you can use just this as the path and use the splat to get the rest of the path.

    const RootComponent = {
      ...
    
      return (
        <Routes>
          ...
          <Route path="/folder/*" element={<ComponentExample />} />
          ...
        </Routes>
      );
    };
    
    import { useParams } from 'react-router-dom';
    
    const ComponentExample = () => {
      const { "*": splat } = useParams();
      console.log(splat); // "child1", "child1/child2", "child1/child2/child3", etc
      ...
    
      return (
        ...
      );
    };
    
    Login or Signup to reply.
  2. If you are using react-router-dom v5+, just set path=folder/*, the router will match every route starting with folder/

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search