ss_millionaire
ss_millionaire

Reputation: 429

How to redirect with flash message react-router 4

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>,
);

Upvotes: 6

Views: 6591

Answers (2)

ss_millionaire
ss_millionaire

Reputation: 429

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

Upvotes: 4

Todd Chaffee
Todd Chaffee

Reputation: 6824

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} /> 
    )
  )} 

Upvotes: 1

Related Questions