Conditional Routing with createBrowserRouter #10478
-
Hi everyone, I would like to create a conditional routing system that depends on the response received from the back end.
I expect a solution like this:
|
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 5 replies
-
@brophdawg11 @huijiewei, |
Beta Was this translation helpful? Give feedback.
-
You can try use loader
|
Beta Was this translation helpful? Give feedback.
-
I have referenced this thread here: #10496, might be worth reading. |
Beta Was this translation helpful? Give feedback.
-
I solved this by wrapping the createBrowserRouter inside a hook and wrapping the RouterProvider in another Context to call the hook. Custom hook: const useRouters = () => {
const [loggedIn, setLoggedIn ] = useState(true)
const PRIVATE_ROUTES: RouteObject[] = [
{
action: loginAction,
element: <Login />,
path: '/'
},
{
path: routesPaths.appCatalog,
element: {loggedIn ? <Start /> : <Navigate replace to={"/"} />}
}, // <----- or
...( loggedIn ? [
{
path: routesPaths.appCatalog,
element: <Start />
}
] : [])
]
const PUBLIC_ROUTES: RouteObject[] = []
return createBrowserRouter([...PRIVATE_ROUTES, ...PUBLIC_ROUTES])
}
export default useRouters main.tsx: const ContextsProvider = () => {
const ROUTER = useRouters()
return (
<OthersProvider>
<RouterProvider router={ROUTER} /> // <---- or only this alone
<OthersProvider />
)
}
export default ContextsProvider |
Beta Was this translation helpful? Give feedback.
I commented in #10223 (comment)