Since Gatsby effectively hides the router, you can't pass props to each page in the way you would with BrowserRouter in Create-React-App. Is there a way to do this in Gatsby? I assume I need to do it somehow in Gatsby-browser.js. I basically want to maintain a state called Step, that is accessible by all pages. Would I have to use Context for this?
CodePudding user response:
I think you would need to use context for that. You'd can add a context in gatsby-browser.js
, as mentioned in the docs: https://www.gatsbyjs.com/blog/2019-01-31-using-react-context-api-with-gatsby/
Their example:
// gatsby-browser.js
import React from "react"
import { ThemeProvider } from "./src/context/ThemeContext"
export const wrapRootElement = ({ element }) => (
<ThemeProvider>{element}</ThemeProvider>
)
CodePudding user response:
You can pass state into a page with Link
(docs), but be mindful of pages being built without state (i.e. statically).
<Link
to={`/photos/`}
state={{ tag }}
>
See more {tag}
</Link>
const PhotosPage = ({ location: { state } }) =>
<div>{state?.tag ? `${tag} photos` : "All photos"}</div>