Skip to content

Commit 19c9c0b

Browse files
fix(gatsby): Wrap Head with <Location> (#36160) (#36165)
Co-authored-by: Jude Agboola <[email protected]>
1 parent 6f0d46b commit 19c9c0b

File tree

4 files changed

+37
-1
lines changed

4 files changed

+37
-1
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import headFunctionExportSharedData from "../../../shared-data/head-function-export.js"
2+
3+
it(`Page with Head Export that uses useLocation works`, () => {
4+
cy.visit(headFunctionExportSharedData.page.pageWithUseLocation).waitForRouteChange()
5+
6+
cy.getTestElement(`location-pathname-in-template`)
7+
.invoke(`text`)
8+
.then(text => {
9+
cy.getTestElement(`location-pathname-in-head`)
10+
.invoke(`attr`, `content`)
11+
.should('equal', text)
12+
})
13+
})

e2e-tests/production-runtime/shared-data/head-function-export.js

+1
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ const page = {
1212
invalidElements: `${path}/invalid-elements/`,
1313
fsRouteApi: `${path}/fs-route-api/`,
1414
deduplication: `${path}/deduplication/`,
15+
pageWithUseLocation: `${path}/page-with-uselocation/`,
1516
}
1617

1718
const data = {
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import * as React from "react"
2+
import { useLocation } from '@gatsbyjs/reach-router';
3+
4+
export default function HeadFunctionExportWithUseLocation() {
5+
const location = useLocation();
6+
7+
return (
8+
<>
9+
<h1>I test that Head export with useLocation hook works</h1>
10+
<p data-testid="location-pathname-in-template">{location.pathname}</p>
11+
</>
12+
)
13+
}
14+
15+
export function Head() {
16+
const location = useLocation();
17+
18+
return <meta data-testid="location-pathname-in-head" name="location" content={location.pathname}/>
19+
}

packages/gatsby/cache-dir/head/head-export-handler-for-browser.js

+4-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import React from "react"
22
import { useEffect } from "react"
33
import { StaticQueryContext } from "gatsby"
4+
import { LocationProvider } from "@gatsbyjs/reach-router"
45
import { reactDOMUtils } from "../react-dom-utils"
56
import { FireCallbackInEffect } from "./components/fire-callback-in-effect"
67
import { VALID_NODE_NAMES } from "./constants"
@@ -81,7 +82,9 @@ export function headHandlerForBrowser({
8182
// In Prod we only call onHeadRendered in FireCallbackInEffect to render to head
8283
<FireCallbackInEffect callback={onHeadRendered}>
8384
<StaticQueryContext.Provider value={staticQueryResults}>
84-
<Head {...filterHeadProps(pageComponentProps)} />
85+
<LocationProvider>
86+
<Head {...filterHeadProps(pageComponentProps)} />
87+
</LocationProvider>
8588
</StaticQueryContext.Provider>
8689
</FireCallbackInEffect>,
8790
hiddenRoot

0 commit comments

Comments
 (0)