Skip to content

Commit

Permalink
fix(gatsby): Support numbers in navigate function (#25611)
Browse files Browse the repository at this point in the history
* fix(gatsby): Support numbers in navigate function

* Fix issue to properly support navigating back by number
  • Loading branch information
blainekasten committed Jul 10, 2020
1 parent 6404fc7 commit 83926c8
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 0 deletions.
Expand Up @@ -33,6 +33,14 @@ describe(`navigation`, () => {
cy.location(`pathname`).should(`equal`, `/`)
})

it(`can navigate using numbers`, () => {
cy.getTestElement(`page-two`).click().waitForRouteChange()

cy.getTestElement(`back-by-number`).click()

cy.location(`pathname`).should(`equal`, `/`)
})

describe(`relative links`, () => {
it(`can navigate to a subdirectory`, () => {
cy.getTestElement(`subdir-link`)
Expand Down
4 changes: 4 additions & 0 deletions e2e-tests/development-runtime/src/pages/page-2.js
Expand Up @@ -3,6 +3,7 @@ import { Link } from "gatsby"

import Layout from "../components/layout"
import SEO from "../components/seo"
import { navigate } from "gatsby"

const SecondPage = () => (
<Layout>
Expand All @@ -12,6 +13,9 @@ const SecondPage = () => (
<Link to="/" data-testid="back-button">
Go back to the homepage
</Link>
<button data-testid="back-by-number" onClick={() => navigate(-1)}>
Navigate by number back
</button>
</Layout>
)

Expand Down
3 changes: 3 additions & 0 deletions packages/gatsby-link/src/index.js
Expand Up @@ -58,6 +58,9 @@ function absolutify(path, current) {
}

const rewriteLinkPath = (path, relativeTo) => {
if (typeof path === `number`) {
return path
}
if (!isLocalLink(path)) {
return path
}
Expand Down
8 changes: 8 additions & 0 deletions packages/gatsby/cache-dir/navigation.js
Expand Up @@ -47,6 +47,14 @@ const onRouteUpdate = (location, prevLocation) => {
}

const navigate = (to, options = {}) => {
// Support forward/backward navigation with numbers
// navigate(-2) (jumps back 2 history steps)
// navigate(2) (jumps forward 2 history steps)
if (typeof to === `number`) {
globalHistory.navigate(to)
return
}

let { pathname } = parsePath(to)
const redirect = redirectMap[pathname]

Expand Down

0 comments on commit 83926c8

Please sign in to comment.