How to redirect with flash message react-router 4
Asked Answered
J

2

6

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>,
);
Jonellejones answered 23/5, 2017 at 3:26 Comment(0)
J
4

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

Jonellejones answered 28/5, 2017 at 5:25 Comment(0)
D
1

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} /> 
    )
  )} 
Descendent answered 23/5, 2017 at 23:2 Comment(1)
Thanks Todd. I answered the question with what worked for me in this case.Jonellejones

© 2022 - 2024 — McMap. All rights reserved.