Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamically pass unknown number of parameters to react router

In my react App, I have the functionality to create Folders and Files. A folder can have any number of folders inside it.

like so

Folder-1
  |_Folder-1-1
  |_Folder-1-2
    |_Folder-1-2-1
    |_Folder-1-2-2
      |_Folder-1-2-2-1
       .
       .
       .

and it can get deeper up to any level. Currently, What I am doing is. There's a component that loads the root folder Folder-1, When you click on Folder-1. I change the route and load another component.

My route Looks like <Route exact path="/clients/:folder" component={ClientFolder} />

But the problem here is I don't know the number of parameters.

The way I envisioned it is

  • You click on Folder-1, URL changes to /clients/Folder-1, Then, it loads all the Folders inside Folder-1, i.e Folder-1-1, and Folder1-2
  • You click on Folder-1-2, URL changes to /clients/Folder-1/Folder-1-2, Loads Files and folders inside Folder-1-2

and so on.

So my question is, How can I have Any number of nested routes using a single route and a single Component

I am using react-router 5

like image 983
Waeez Avatar asked May 24 '19 04:05

Waeez


2 Answers

Remove the exact match it would work

You can refer to this sample https://codesandbox.io/s/great-tu-yr85t

like image 100
Sandeep Ranga Avatar answered Sep 24 '22 00:09

Sandeep Ranga


This can be done by using the match all *. Something like:

<Route path="/clients/*">

Whatever path is passed after /clients will then be available in match.params["0"].

like image 26
Merlin Mason Avatar answered Sep 23 '22 00:09

Merlin Mason