Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 206
MyName Avatar asked Sep 22 '17 09:09

MyName


People also ask

How do you redirect on page reload in React?

If set to true, the browser will do a complete page refresh from the server and not from the cached version of the page. import React from 'react'; function App() { function refreshPage() { window. location. reload(false); } return ( <div> <button onClick={refreshPage}>Click to reload!

How do you stay at the same page after page reload in React?

Using LocalStorage — Class Components Now let's say if we want to keep this count value persist when the page reloads, we can do that by simply introducing localStorage. As you can see, now we store the state value whenever we call the setState method. This is a simple approach to achieve what we want.

How do I redirect to another page in React JS using navigate?

To redirect to another page on button click in React: Use the useNavigate() hook, e.g. const navigate = useNavigate(); . Call the navigate() function, passing it the path - navigate('/about') . The navigate() function lets us navigate programmatically.


1 Answers

Try window.location.href instead of browserHistory.push. This will help.

onUnload() {
       window.location.href = "/";
}

Here is an example:

https://stackblitz.com/edit/react-rbfoic?file=src/App.js

like image 182
Pulsara Sandeepa Avatar answered Oct 13 '22 21:10

Pulsara Sandeepa