skip to Main Content

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?

2

Answers


  1. 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('/');
    
    Login or Signup to reply.
  2. 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.

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