Here's what i'm trying to achieve: When a user tries to access a protected page on my ReactJS site, i want to redirect them to the home page with a flash message saying "Please log in" or something similar. How do i achieve this with react-router v4. Here's what i have so far:
<Router>
<div>
<Switch>
<Route path="/" component={Home} />
<Route
exact path="/source" render={() => (
isAuthenticated() ? (
<Source />
) : (
<Home /> //I want to Redirect to the Home Page with a flash message if user is not logged in
)
)}
/>
<Route path="/contact" component={ContactUs} />
</Switch>
</div>
</Router>,
);
Here's what worked for me: I used the Redirect method that comes with react-router v4. It enables you achieve this with ease.
<Route
exact path="/source" render={() => (
isAuthenticated() ? (
<Source />
) : (
<Redirect
to={{
pathname: '/',
state: 'Please sign in'
}}
/>
)
)}
/>
You can read more about Redirect here: React Router v4 - Redirect
How about sending a logged in property to the <Home>
component and then the home component can look at that property and render the flash message if needed:
exact path="/source" render={() => (
isAuthenticated() ? (
<Source />
) : (
<Home loggedIn={isAuthenticated} />
)
)}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With