Reputation: 575
Trying to create a file renderer but I do not know how to create in a right way. The snippet that I have is that one but is super repetitive:
<Routes>
<Route path='/explorer' element={<Files>}>
<Route path=':root' element={<Files>}>
<Route path=':branch' element={<Files>}>
<Route path=':leaf' element={<Files>} />
...
</Route>
</Route>
</Route>
</Routes>
Examples:
If I use useParams
hook from react-router-dom
sometimes some params would be undefined and I would like to ignore these params (looping all params I could do it but I do not think is the best practise)
With that params after I create an array and make a request to display all the files or the folders of the selected path (/explorer/home/username)
Is it some way to set a generic number of params for just one component and get a params
object with just the need it params?
<Routes>
<Route path='/explorer' element={<Files>}>
<Route path='??' element={<Files>}>
</Route>
<Routes>
Upvotes: 2
Views: 612
Reputation: 202696
Just a suggestion I have for a simple way to manage this would be to render a single route with no path parameters and a trailing wildcard character "*"
to continue matching after the first path segment.
Example:
<Routes>
<Route path="/explorer/*" element={<Files />} />
</Routes>
The Files
component will then access the entire location.pathname
and apply a little string manipulation to get the file/directory structure from the URL path segments.
Example:
const Files = () => {
const { pathname } = useLocation();
const path = pathname
.slice(1) // remove leading "/"
.split("/") // split path directories
.slice(1); // remove leading "explorer" route path
return (
...
);
};
pathname | path array |
---|---|
/explorer/home |
["home"] |
/explorer/home/username |
["home", "username"] |
/explorer/home/username/documents |
["home", "username", "documents"] |
/explorer/home/username/documents/math/exercises |
["home", "username", "documents", "math", "exercises"] |
What you do with path
from here is up to you.
The other solution I'd proposed was to pass the path as a query parameter, i.e. "/explorer?path=/home
, and apply a similar path string processing. Perhaps something like the following:
const [searchParams] = useSearchParams();
const stringPath = searchParams.get('path');
const path = stringPath
.slice(1) // remove leading "/"
.split("/"); // split path directories
Upvotes: 1