20

I have a router like this:

<Route path="/blog/:date/:folder" render={(props: any) => <Home />

It works with this:

http://localhost/blog/2017-05-20/test

However, :folder can have slashes (sub-dir) and i want to parse all path at once in folder.

This is not working:

http://localhost/blog/2017-05-20/test/sub/dir

In this situation, I only get test. I want to get :folder as test/sub/dir as a whole.

Is there any way to achieve this with React Router?

Expected:

:date => '2017-05-20'
:folder => 'test/sub/dir'

Actual:

:date => '2017-05-20'
:folder => 'test'
Dennis
  • 1,805
  • 3
  • 22
  • 41

2 Answers2

39

Yes, you can do this by adding a + to your Route path. So, like this:

<Route path="/blog/:date/:folder+" ... />

This library is being used for matching the path. So for more advanced matching cases this is a better place to look at then the React Router docs.

Jap Mul
  • 17,398
  • 5
  • 55
  • 66
  • 6
    Please not that the library referenced is not used with React Router v6, and this solution does not work. Instead a wildcard `*` may work depending on your usecase. – pgjones Dec 01 '21 at 14:29
  • 2
    For me, the `.../:folder*` will resolve to the route, but the folder param in the component resolves only to the first segment of the :folder (ex, 'test/sub/dir` ... folder useParams would just be `test`) – empire29 Mar 14 '22 at 15:48
  • Discussed further in this issue, with no resolution: https://github.com/remix-run/react-router/issues/8254 – Lucas Wiman Oct 13 '22 at 02:17
1

You can recursively embed components if they're rendered by a Route - you could then check this.props.match for a path name, for example, in your base Router, you'd have the basic route, /blog/:date, which renders a Home component.

Then inside the Home component, you could render another Route (it still works from here, despite not being an immediate child of the Router) with a set up like

<Route path={`${this.props.match.url}/:folder`} component={Folder} />

Then inside the Folder component you would render the same Route, which will progressively render sub-components for each /:folder in the path.

The match object also includes isExact which you could use to determine if you're on the last level of the folder structure from the URL.

Source: See this example of embedded routes.