Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I have an undefined numbers of multiple dynamic path segments in a route in React that point to the same component?

I need to have a route that can receive many different path segments dynamically like "https://website/folder1/folder2/folder3" and so on.

Each time a user can create a new folder inside another folder and can be navigated to the same component.

Basically what I am trying to achieve is to create a page like Google drive with a folders and subfolders system, where an user can create a folder and subfolders inside it and upload documents and videos and other users can see them when they go in the nested specific folder. In order to keep track of the location of the user and get the right documents/files to show from the server I was thinking to use the url to get the last path segment to know what data I need to ask the server, I also need the full path for a breadcrumb.

I found some sources around that suggested using "+" after the id path segment but it is not working:

<Route path="/area/:folder+" element={<AreaComponent />} />

The problem is this doesn't work.

I am using [email protected].

How can I implement this?

like image 304
Andrea D_ Avatar asked Oct 30 '25 23:10

Andrea D_


2 Answers

React-Router v6 removed support for REGEXP in the route paths. You could use path="/area/*" and then grab the rest of the path from the splat.

<Route path="/area/*" element={<AreaComponent />} />

Example URL: "https://website/area/folder1/folder2/folder3"

AreaComponent

import { useParams } from 'react-router-dom';

...

const { "*": splat } = useParams();
console.log(splat); // "folder1/folder2/folder3"

From here you can use simple string manipulation to handle/extract information from the rest of the path.

See route Splats for more details.

like image 112
Drew Reese Avatar answered Nov 01 '25 13:11

Drew Reese


In React Router version 6, dynamic nested routes can be a bit different to set up compared to previous versions. The + syntax you mentioned is not used in the same way as in previous versions. Instead, React Router v6 uses a * to capture multiple segments.

<Route path="/area/*" element={<AreaComponent />} />

you can access the captured segments using the useParams

const { '*': folders } = useParams();
const folderNames = folders.split('/');
like image 41
Danish Shaikh Avatar answered Nov 01 '25 14:11

Danish Shaikh