Frontend Router

Overview

The frontend-router package is used for managing client-side routing and accessing browser history.

Import

frontend-router is already pre-installed on every Shogun Frontend store. To import:

import { useRouter } from 'frontend-router'

Basic usage

With useRouter hook, you can access the router object and its properties inside any component/section:

import React from 'react'
import { useRouter } from 'frontend-router'

const MyComponent = () => {
  const router = useRouter()

  return (
    <p>You are currently at: {router.pathname}</p>
  )
}

export default MyComponent

See the table below for all router properties available.

Methods usage

push

The push method handle client-side navigation. It accepts the following parameters:

  • url: A string indicating the URL to which to navigate.
  • as: A string indicating the URL that will be shown in the browser. This is optional.
  • options: An object with the following options:
    • scroll: A boolean that controls whether the page should scroll to the top after navigation. This is true by default.
    • shallow: A boolean that allows updating the path of the current page without rerunning.
    • getStaticProps: This is false by default.
    • getServerSideProps: This is false by default.
    • getInitialProps: This is false by default.
    • locale: A string indicating the locale of the new page. This is optional.
import React from 'react'
import { useRouter } from 'frontend-router'

const MyComponent = () => {
  const router = useRouter()

  return (
    <React.Fragment>
      {/* Simple usage */}
      <button onClick={() => router.push('/contact')}>
        Go to contact page
      </button>

      {/* Advanced usage */}
      <button
        onClick={
          () => router.push(
            '/profile',
            '/my-profile',
            {
              scroll: false,
              shallow: true,
              locale: 'en'
            }
          )
        }
      >
        Go to profile page
      </button>
    </React.Fragment>
  )
}

export default MyComponent

replace

The replace method replaces the current browser history, instead of adding the URL to the browser history stack. Its API is the same as the router.push.

import React from 'react'
import { useRouter } from 'frontend-router'

const MyComponent = () => {
  const router = useRouter()

  return (
    <button onClick={() => router.replace('/contact')}>
      Go to contact page
    </button>
  )
}

export default MyComponent

reload

The reload method is the equivalent of clicking on the browser's refresh button.

import React from 'react'
import { useRouter } from 'frontend-router'

const MyComponent = () => {
  const router = useRouter()

  return (
    <button onClick={() => router.reload()}>
      Reload this page
    </button>
  )
}

export default MyComponent

back

The back method is the equivalent of clicking on the browser's back button.

import React from 'react'
import { useRouter } from 'frontend-router'

const MyComponent = () => {
  const router = useRouter()

  return (
    <button onClick={() => router.back()}>
      Go back
    </button>
  )
}

export default MyComponent

events

The events method responds to the following events during navigation:

  • routeChangeStart(url, { shallow }): Triggered when a route starts to change.
  • routeChangeComplete(url, { shallow }): Triggered when a route change is finished.
  • routeChangeError(err, url, { shallow }): Triggered when an error occurs during routes transitions, or when a route load is cancelled (indicate by err.cancelled).
  • beforeHistoryChange(url, { shallow }): Triggered before changing the browser's history.
  • hashChangeStart(url, { shallow }): Triggered when the URL's hash will change but not the page.
  • hashCompleteStart(url, { shallow }): Triggered when the URL's hash has changed but not the page.

🚧

Important

events must be used inside of an useEffect.

import React from 'react'
import { useRouter } from 'frontend-router'

const MyComponent = () => {
  const router = useRouter()
  
  React.useEffect(() => {
    const handleRouteChange = (url) => {
      console.log(`URL is ${url}.`)
    }
    
    router.events.on('routeChangeStart', handleRouteChange)
    
    return () => {
      router.events.off('routeChangeStart', handleRouteChange)
    }
  })

  return (
    <button onClick={() => router.push('/')}>
      Go to home page
    </button>
  )
}

export default MyComponent

Router object output

name

type

description

location

{}

The equivalent of window.location.

pathname

string

The equivalent of window.location.pathname.

query

{}

The equivalent of window.location.search. It returns an object with the URL's query string. If the URL does not have query string, it returns an empty object.

push

function (url, as, options) {}

For client-side routing navigation.

replace

function (url, as, options) {}

Replaces the current browser history instead of appending it to the stack.

reload

function () {}

The equivalent of window.location.reload(). It reloads the current page.

back

function () {}

The equivalent of window.history.back(). It navigates back in history, like clicking the browser's back button.

events

{}

Used to listen to events during the page's navigation. See examples above for more.

isReady

boolean

This should be used inside of an useEffect. Confirms when router fields are up to date and ready to use.


Did this page help you?