Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>,
);
like image 767
ss_millionaire Avatar asked May 23 '17 03:05

ss_millionaire


2 Answers

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

like image 200
ss_millionaire Avatar answered Nov 19 '22 18:11

ss_millionaire


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} /> 
    )
  )} 
like image 1
Todd Chaffee Avatar answered Nov 19 '22 16:11

Todd Chaffee