1

I am creating a react/Gatsby website and am trying to get the navigation working an need some guidance

So basically I have a site on a domain like: https//mysite.com

When navigating in the site my route gets added to the domain, like so: https//mysite.com/page1, https//mysite.com/page2 etc.

When I refresh the browser I want the site to reload the website to its origional state, ie, https//mysite.com.

When I do reload from /page2, for example, the site seems to remember the last position. So on a reload I still have https//mysite.com/page2 in the address bar, whereas I want the site to go to the home page.

Is this possible?

Thanks

RedLizard
  • 41
  • 2
  • You say "reset the app" in the title. Gatsby builds real HTML pages. `/page2` contains an index.html just like you would with plain old HTML. There is nothing to reset. Unlike plain React where you can reset the app, Gatsby will reload the code for `/page2`. What you want is a redirect to the root `/` when the user reloads. Please calrify your question. – EliteRaceElephant Oct 13 '19 at 16:58
  • Yes you are correct, it will be a website, I mistakenly mentioned app because it will also be wrapped in Showpad as an app. – RedLizard Oct 13 '19 at 19:37
  • The redirect to the root on reload sounds the best option to me. I understand that the page currently viewed, would be the one that reloads, but for some reason my client wants to be redirected to the homepage on page refresh. Any help would be great fully received. – RedLizard Oct 13 '19 at 19:41

1 Answers1

0

See this question for how to detect a page reload (such as pressing F5). The second most upvoted answer recommends this code for detecting the refresh and triggering another function:

componentDidMount() {
    window.onbeforeunload = function() {
        this.onUnload();
        return "";
    }.bind(this);
}

Gatsby uses @reach/router under the hood. So use Gatsby Link to redirect to your root page:

import { navigate } from "gatsby"

componentDidMount() {
    window.onbeforeunload = function() {
        this.onUnload();
        return "";
    }.bind(this);
    navigate("/"); // redirect to your root page here
}

The user will be able to go back to the previous page. If you don't want this you replace the history like this:

navigate("/", { replace: true });
EliteRaceElephant
  • 7,744
  • 4
  • 47
  • 62