I have the following code in my router.tsx file:
<Route path='/portal/edit' element={<PrivateRoute/>}>
{props.editObject != null &&
<Route path='/portal/edit' element={<Edit
editObject={props.editObject}
/>}/>
}
{props.editObject == null &&
<Route path="*" element={<Navigate replace to="/portal/overview" />} />
}
</Route>
What is the code doing?
First, I am checking if the User is Authenticated. If the user is authenticated we are checking if the prop editObject
is null or not. The user is not allowed to enter the page when editObject is null. If the object is null I want to redirect back to 'overview'.
Any route works except the <Navigation />
-links. I checked in the debugger and the code is going to <Navigate replace...
but the browser is showing me only a blank page without any useful information in the console.
CodePudding user response:
After many attempts, I found a solution. Unfortunately I can't explain why it works, but it works:
In route-path you have to set the same path like in the higher hierarchy. So instead of writing path="*" you have to write 'portal/edit'
<Route path="/portal/edit" element={<Navigate replace to="/portal/overview" />} />
CodePudding user response:
Issue
<Route path='/portal/edit' element={<PrivateRoute/>}> {props.editObject != null && <Route path='/portal/edit' element={<Edit editObject={props.editObject} />}/> } {props.editObject == null && <Route path="*" element={<Navigate replace to="/portal/overview" />} /> } </Route>
The issue here is that route paths that don't start with a leading "/"
character are considered to be relative paths. The nested Route
with path="*"
resolves to a path like "/portal/edit/*"
. I suspect you should have seen a "no route matches....." type warning in the console.
Solution
It seems you are basically conditionally rendering the element
prop, i.e. either the routed Edit
or Navigate
component.
An optimized suggestion. Keep the outer PrivateRoute
as a layout component but remove the path
prop so the inner routes can do the matching. Render the inner route and conditionally render either the Edit
or Navigate
redirect.
<Route element={<PrivateRoute/>}>
<Route
path='/portal/edit'
element={props.editObject !== null
? <Edit editObject={props.editObject} />
: <Navigate replace to="/portal/overview" />
}
/>
</Route>