Maria Jeysingh Anbu
Maria Jeysingh Anbu

Reputation: 3312

React Router | load component only on page refresh

I'm using React Router v4 Browser Router. My scenario is I have call login page on every page refresh (Browser Refresh click or F5)

Route

 <Router history={history}>
        <div>
          <Spin spinning={this.props.isloading}>
            <Switch>
              <Route path="/login" component={Login} />
              <Route path="/Dashboard" component={Dashboard} />
              <Route path='*' component={NotFound} />
            </Switch>
          </Spin>
        </div>
      </Router>

I need to load login component on page refresh so I need something like below

<Refresh path="/login" component={Login} />

Upvotes: 2

Views: 4666

Answers (3)

Pawan Bishnoi
Pawan Bishnoi

Reputation: 2127

It happens to me and the issue was i am importing Router from react-router-dom instead of BrowserRouter as Router.

Upvotes: 2

Kevin Raoofi
Kevin Raoofi

Reputation: 1033

Just do something like:

const Refresh = ({reload, children}) => reload ? children : null;

...

<Refresh reload={performance.navigation.type === 1}>
    <Redirect to="/login"/>
</Refresh>

Based on:

Upvotes: 0

Anurag Awasthi
Anurag Awasthi

Reputation: 6233

Create a componentDidMount method in your root component, which will be responsible for logging in your user by redirecting the user to /login.

Then add a event listener for page refresh which will logout the user for any page refresh.

componentDidMount(){
    if(!userLoggedIn()){
        //redirect to login
        history.push("/login")
    }

    window.addEventListener('beforeunload', logoutTheUser);
    /* if you are not maintaining a session, you dont need this
      as user will be logged out automatically on page refresh.*/
}

Upvotes: 0

Related Questions