Good day, Would you be able to help me regarding my problem with react-router v6's nested element, specifically, the child element?
Let's say I have this routing
<Routes>
<Route path="customer" element={<CustomerIndex />} >
<Route path=":customeId" element={<CustomerDetail />} />
<Route path="create" element={<CustomerForm />} />
</Route>
</Routes>
And the "CustomerIndex" component
function CustomerPage(){
const {customerId} = useParams();
return (
<>
//.....Bla bla bla index table etc etc etc end of thinking capacity
<ComponentToDisplayModal display={Boolean(customerId)} >
<Outlet />
</ComponentToDisplayModal>
</>
);
}
Now if I go to "/customer/3", the CustomerIndex would display the Modal Component (display=true) and the because the "customerId" constant is defined by the useParams
But if I would like to show "CustomerForm" component by navigating to "/customer/create", of course, the 'ComponentToDisplayModal" wouldn't be displayed because customerId is null.
So, of course, I would like to have this instead
const display = Boolean(customerId) || isAnyChildPath;
.....
<ComponentToDisplayModal {...{display}}>
Now, how could i set "isAnyChildPath" constant to "TRUE" if path is "/customer/*", and "FALSE" if path is "/customer", or maybe, check wether would return a componen (eg. "/customer/create", "/customer/4"), or not ("/customer") ?
For now, I just use the manual method of
const location = useLocation();
const display = Boolean(customerId) || location.pathname === "/customer/create"
But I would like to learn if there is exist a more elegant method, in case I need to add several other static childs in the future.
Thank you very much.
I think you could simplify the child route check a bit by using the useMatch hook and check if the current path matches either child route instead of testing by any route path params.
declare function useMatch<ParamKey extends string = string>( pattern: PathPattern | string ): PathMatch<ParamKey> | null;Returns match data about a route at the given path relative to the current location.
The idea is that when the route matches a defined match object is returned, otherwise null is returned for non-matches.
"/customer/:path" can match both "/customer/:id" and "/customer/create".
Example:
function CustomerPage(){
const isMatch = useMatch("/customer/:path");
return (
<>
//.....Bla bla bla index table etc etc etc end of thinking capacity
<ComponentToDisplayModal display={Boolean(isMatch)} >
<Outlet />
</ComponentToDisplayModal>
</>
);
}