REACT router re-render

Anyone come across this problem? When the user logs out via a logout route this code gets executed:

import React from 'react'; // needed
import ReactDOM from 'react-dom';
import Home from './components/layout/Home.js';
import Login from './Login/Login';
import PollDetails from './components/layout/PollDetails.js';
import EditPoll from './components/presentation/EditPoll.js';
import CreatePoll from './components/presentation/CreatePoll';
import Container from './components/containers/Container.js';
import {Route,Router,browserHistory,IndexRoute} from 'react-router';
import Auth from './utils/Auth';

const mountNode = document.getElementById('root');

ReactDOM.render( 
  <Router history={browserHistory}>
    <Route path="/" component={Container} >
      <IndexRoute component={Home} />
      <Route path="login" component={Login} />
      <Route path="logout" onEnter={(nextState, replace) => {
        Auth.deauthenticateUser();
        
        console.log('Logging out src/app.js');
        Auth.clearCookie();
        // change the current URL to /
        replace('/');}} />
      <Route path="Polldetailfull/:id" component={PollDetails}  />
      <Route path="Editthepoll/:id" component={EditPoll}  />
      <Route path="createPoll" getComponent={(location, callback) => {
        if (Auth.isUserAuthenticated()) {
          callback(null, CreatePoll);
        } else {
          callback(null, Home);
        }
      }} />
    </Route>
  </Router>,mountNode);

However, the replace('/'); sends you back to the home page but doesn’t re-render any components. Note there is no state to change here. Do I need one to force the re-render?

Note, if you press refresh on the browser the desired behaviour happens.

Not sure if this helps, but I have used the react-router-dom package before to redirect by pushing history to the root route using withRouter and history.push('/').

1 Like

React Router changes the context and does not change any props. This means that React doesn’t trigger a re-rendering.
You can investigate if this is the case by using the React Dev extension tool and see if only the context changes and not any props passed.

This can be solved with the usage of shouldComponentUpdate by making the component aware of the route location change.
However things get a little more complicated if the component is connected to a store (eg redux-connect) or is a PureComponent.

This page has a good explanation on it and what could you do to fix it.
Hope it helps.

2 Likes