[FIXED] Using Gatsby Link with TypeScript

Issue

I’m using Gatsby Link with TypeScript and I want to pass parameters to linked component from source component.

Gatsby’s reference says as following.

Sometimes you’ll want to pass data from the source page to the linked page. You can do this by passing a state prop to the Link component or on a call to the navigate function. The linked page will have a location prop containing a nested state object structure containing the passed data.

And the sample code with JavaScript is following.

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} />
  }
}

But with TypeScript, I don’t know which type I should use for props to get the location prop. I tried GatsbyLinkProps as props type of linked component but it doesn’t contain location prop and its state prop was undefined even though I had passed state prop from source component.

Any ideas?

Solution

location is an object type of PageProps and would need to be passed from your page component to the Photo component (assuming Photo isn’t a page in the coding example).

import type { PageProps } from 'gatsby';

interface PhotoProps {
  location: PageProps['location'];
  photoId: string;
}

const Photo = ({ location, photoId }: PhotoProps) ...

Answered By – Dwayne Gardner

Answer Checked By – David Marino (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published