Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass data between pages in Gatsby?

Tags:

gatsby

I'm trying to pass data when I route to a new page using in Gatsby (V2)

I am hoping to then be able to retrieve the data on that page. Is this possible? I have researched this a lot with no luck so I feel as though I must be missing something... Thank you

like image 813
davl Avatar asked Oct 18 '25 23:10

davl


1 Answers

If you want to pass props, it can be as simple as the following example from the docs:

const PhotoFeedItem = ({ id }) => (
  <div>
    {/* (skip the feed item markup for brevity) */}
    <Link
      to={`/photos/${id}`}
      state={{ fromFeed: true }}
    >
      View Photo
    </Link>
  </div>
)

const Photo = ({ location, photoId }) => {
  if (location.state.fromFeed) {
    return <FromFeedPhoto id={photoId} />
  } else {
    return <Photo id={photoId} />
  }
}

The reference in the docs includes an egghead video of the behaviour to clarify it.

https://www.gatsbyjs.org/docs/gatsby-link/#pass-state-as-props-to-the-linked-page

You can also do some advanced routing by using create pages, and generate pages programatically. This is a bit more advanced but useful if your gatsby app is getting a little complex.

https://www.gatsbyjs.org/docs/reach-router-and-gatsby/

like image 176
Christos Hrousis Avatar answered Oct 22 '25 04:10

Christos Hrousis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!