Search code examples
reactjsreact-routerflash-messagereact-router-v4

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

Solution

  • 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