Gatsby's `navigate` function to navigate to the same page?

Viewed 1380

Is it possible to use Gatsby's navigate function to navigate to the same page?

For instance, I built a search component that lives on the navigation bar, therefor accessible on any page. Once users perform search, they get routed to the Search Results page via navigate(/search-results).

If they are on that page, and want to perform the search again, that navigate function does not work, hence no results display.

I'm aware I could do a window.location.reload() but wanted to see if there are other ways.

1 Answers

Gatsby's navigation (Link component or navigate function) doesn't support parameters per se as you want to.

From Gatsby's docs:

Neither <Link> nor navigate can be used for in-route navigation with a hash or query parameter. If you need this behavior, you should either use an anchor tag or import the @reach/router package—which Gatsby already depends upon—to make use of its navigate function, like so:

So, that said, you have two approaches:

  • Importing the navigation from @reach/router:

    import { navigate } from '@reach/router';
    
    
      onClick = () => {
        navigate('?foo=bar');
      }
    
  • Using window.location as you pointed

Of course, the @reach/router will give you a smoother workaround.

Related