Shatiz
Shatiz

Reputation: 817

How to access Gatsby Create Page template GraphQL variable inside JSX?

How can I access and use $category within <div> as <h2>$category</h2> ?

import React from "react"
import { graphql } from "gatsby"
import Layout from "../components/layout"
export default ({ data }) => {
  const posts = data.posts
  return (
    <Layout>
      <div>
        <h1>List of Posts</h1>
      </div>
    </Layout>
  )
}
export const query = graphql`
  query($category: String!) {
    posts( { category: { name: $category} }) {
      summary
    }
  }
`

Please note that GraphQL returns a list of objects (instead of one object) in my case. I can read it from first item in the list but wondering if there is any better way. Also in some cases, list could be empty, so that'll not work.

Upvotes: 0

Views: 143

Answers (2)

LekoArts
LekoArts

Reputation: 1569

You can access category from the property pageContext as shown here: https://www.gatsbyjs.org/docs/creating-and-modifying-pages/#pass-context-to-pages

Upvotes: 0

EliteRaceElephant
EliteRaceElephant

Reputation: 8162

Currently, you can't use variables inside GraphQL queries. The problem is that these GraphQL queries are extracted during the Gatsby build process before any variables are instantiated. See this github issue:

There is no other way to pass variables, pages are created at gatsby-node level. Your only option is inline variables like I described above, either in page query or in useStaticQuery. We have plans to make useQuery accept variables, but there is no ETA.

Upvotes: 1

Related Questions