React js Redirect to main page when you try to refresh other pages

Viewed 16228

I need to redirect to main page when user refreshes other pages. It' s my attempt to add event listener for page refresh. But it doesn't work and I have Router.js?cf42:125 Uncaught RangeError: Maximum call stack size exceeded in browser. Could you advise me how to cope with this error?

import {browserHistory} from 'react-router';

class MyComponent extends React.Component {
    constructor(props, context) {
        super(props, context);
        this.onUnload = this.onUnload.bind(this);
    }

    componentDidMount() {
       window.addEventListener('beforeunload', this.onUnload);
    }

    componentWillUnmount() {
        window.removeEventListener('beforeunload', this.onUnload);
    }

    onUnload() {
        browserHistory.push('/');
    }

    render() {
        ...
    }
}

UPD: I have fixed RangeError. Now MyComponent's page is redirected to main page but after that it opens again. I think that this happens because redirect doesn't stop page refresh.

5 Answers

You need to bind onUnload() - add the following to your constructor:

this.onUnload = this.onUnload.bind(this);

Also, the correct event name for the listener is onbeforeunload

componentWillMount() {
sessionStorage.reload = true;
}
render() {
if(sessionStorage.reload && history.location.pathname!=='/') {
console.log(this.props);
  sessionStorage.reload = "";
  history.push('/login');
} 
return (
  <Router history={ history }>
  <div className="App">
    <Switch>
      <>
      <Route path="/" exact strict component={ Loginpage } />
      <Route path="/mapview" exact component={ GoogleMap } />
      <Route path="/dashboard" exact component={ Dashboard } />
      <Route path="/tripList" exact component={ TripList } />
      <Route path="/createTrips" exact component={ CreateTrips } />
      <Route path="/trace" exact component={ trace } />
      <Route path="/vehicleinfo" component={ vehicleinfo } />
      <Route path="/MyPeople" component={ MyPeople } />
      <Route path="/AddForm" component={ MyPeople } />
      <Route path="/ListView" component={ ListView } />
      <Route path="/fleetAlerts" component={FleetAlerts} />

      <Route path="/login" exact component={ Loginpage } />
      </> 
    </Switch>
  </div>
  </Router>
)  }

try this simple way

 import {  useHistory } from "react-router-dom";
   let history = useHistory();

  function your(){
     let confirm = () => {
alert(
  `you will get redirect to home on click ok`
);
window.location.reload(history.push("/"));
         };

        return(
        <button className="redirect_confirm" onClick={confirm}>
          Confirm
        </button>
            )
                   }

If you are using React-Router and your home component path is /

onUnload() {
    this.context.router.push('/');
}

Make sure your routes file is correct as well.

const routes = (
<Route path="/" component={App}>
 <IndexRedirect to="/home" component{Home}/>
  //all other routes
</Route>
)
Related