How to redirect using react-router 4 flash message

Here's what I'm trying to achieve: When a user tries to access a secure page on my ReactJS site, I want to redirect them to the home page with a flash "Please login" or something similar. How to achieve this with action-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>,
);

      

+3


source to share


2 answers


Here's what worked for me: I used the Redirect method that comes with react-router v4. This allows you to deal with it easily.

<Route 
      exact path="/source" render={() => (
        isAuthenticated() ? (
          <Source />
        ) : (
          <Redirect 
            to={{
              pathname: '/',
              state: 'Please sign in' 
            }} 
          />
        )
      )} 
    />

      



You can read more about Redirect here: React Router v4 - Redirection

+1


source


How to send dispatched property to component <Home>

and then home component can look at that property and display flash message if needed:



  exact path="/source" render={() => (
    isAuthenticated() ? (
      <Source />
    ) : (
      <Home loggedIn={isAuthenticated} /> 
    )
  )} 

      

+1


source







All Articles