Reputation: 10021
I have a react router structure like this:
<HashRouter basename='/'>
<Switch>
<Route exact path='/'>
<Component1 />
</Route>
<Route path='/2'>
<Component2 />
</Route>
<Route path='/3'>
<Component3 />
</Route>
<Route path='/not-authorized'>
<NotAuthed />
</Route>
</Switch>
</HashRouter>
what I want to happen is, whenever I go to any of these routes, I want to run some logic to determine if the user is authorized to see them. If not, they should always get re-directed to /not-authorized
. So if I navigate directly (via browser address bar OR via client-side redirect) to /
or to /2
etc... I should always run the logic to determine if I should be redirected to /not-authorized
. But if I am authorized, I should go to the appropriate route, so if I was attempting to go to /2
it should correctly bring to me /2
if I'm authorized.
Basically my question is; is there a built-in way (prop that I can pass to the Switch) for react router to do this or do I need to manually add logic to check auth on each route's component and redirect away if not authed?
Upvotes: 0
Views: 2202
Reputation: 64
I'd go with something like:
<HashRouter basename='/'>
<Switch>
<Route exact path='/'>
{ condition ? <Component1 /> : <ComponentForUnauthorized/> }
</Route>
<Route path='/2'>
{ condition ? <Component2 /> : <ComponentForUnauthorized/> }
</Route>
<Route path='/3'>
{ condition ? <Component3 /> : <ComponentForUnauthorized/> }
</Route>
</Switch>
</HashRouter>
Or even based on another answer React router with conditions
<HashRouter basename='/'>
<Switch>
<Route exact path="/" component={()=>isAuthorised ? <Component1/> <Unauthorised/>}/>
</Switch>
</HashRouter>
However, there is also an official way given in router official docs, with redirect, which is I believe is even better: https://reactrouter.com/web/api/Redirect
<HashRouter basename='/'>
<Switch>
<Route exact path="/">
{loggedIn ? <Redirect to="/dashboard" /> : <PublicHomePage />}
</Route>
</Switch>
</HashRouter>
Upvotes: 1