GraphQL
🔔️ Important
Query: is used for files under pages/ directories.
StaticQuery: is used for files under components/ or any other directory. More info...
useStaticQuery: Instead of StaticQuery, you can use the hook useStaticQuery, which is easier. More info...
Query: is used for files under pages/ directories.
StaticQuery: is used for files under components/ or any other directory. More info...
useStaticQuery: Instead of StaticQuery, you can use the hook useStaticQuery, which is easier. More info...
How to query siteMetadata from gatsby-config.js
For files under pages/
import React from "react"import { graphql } from 'gatsby'const IndexPage = ({data}) => {return (<header><h1>{data.site.siteMetadata.title}</h1></header>)}export const query = graphql`query IndexPageQuery {site {siteMetadata {title}}}`export default IndexPage
For components under any directory (StaticQuery)
import React from 'react'import { StaticQuery, graphql } from 'gatsby'const Header = () => (<StaticQueryquery={graphql`query HeadingQuery {site {siteMetadata {title}}}`}render={data => (<header><h1>{data.site.siteMetadata.title}</h1></header>)}/>)export default Header
For components under any directory (useStaticQuery)
import React from 'react'import { useStaticQuery, graphql } from 'gatsby'const Header = () => {const data = useStaticQuery(graphql`query HeaderQuery {site {siteMetadata {title}}}`)return (<header><h1>{data.site.siteMetadata.title}</h1></header>)}export default Header
How to query several images from source files
Case example: How to get all files with extension ".webp" and ".jpeg" from directory "images"
- On gatsby-configure.js, configure gatsby-source-filesystem plugin in order to fetch data from particular directories, in this case /images/
module.exports = {plugins: [{resolve: `gatsby-source-filesystem`,options: {name: `images`,path: `${__dirname}/images/`,},},],}
- Create the query. Note that in order to filter by directory, we actually use the name you specified in the gatsby-config.js file by using the filter sourceInstanceName in the query:
export const query = graphql`query MyQuery {allFile(filter: {sourceInstanceName: {eq: "images"}, extension: {regex: "/(jpeg)|(webp)/"}}) {edges {node {namerelativePath}}totalCount}}`
Note that relativePath will yield the actual name of the file.