Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access context variable within the template component in Gatsby?

Within a react component in a Gatsby app, I understand how to use a context variable within the graphql queries, e.g:

export const tagPageQuery = graphql`
  query TagPage($tag: String) {
    site {
      siteMetadata {
        title
      }
    }
    allItem(filter: { tags: { in: [$tag] } }) {
      totalCount
      edges {
        node {

          id
          move
          videoUrl

$tag is a string that allows me to filter. I get that. But is there someway to access this value within the component itself? I can access the data that the graphql query gets, but can't get the variable outside of Graphql. I would love to have it be {context.tag} or something like that, to be able to use that value within my h1. I've gone through the Gatsby GraphQL reference and no dice. It feels like getting this value should be easy but I'm wondering if I need to use something like a getContext hook?

like image 528
Kyle Pennell Avatar asked Jun 28 '19 13:06

Kyle Pennell


1 Answers

Amazing what a 10 minute mini nap can do! Indeed, you can access context variables with the pageContext prop detailed here: https://www.gatsbyjs.org/docs/creating-and-modifying-pages/#creating-pages-in-gatsby-nodejs

const TagPage = ({ data, classes , pageContext}) => {

Adding pageContext to my props allowed me to get access to $tag.

like image 139
Kyle Pennell Avatar answered Oct 14 '22 03:10

Kyle Pennell