GraphQL Fragments
GraphQL Fragments are snippets of queries, which are used to standardise how data about objects is retrieved from the GraphQL server.
A simple example is the ResponsiveImage fragment, which comes pre-bundled with the starter theme, and looks like this:
fragment ResponsiveImage on MediaItem {
mediaItemUrl
caption
srcSet
altText
mediaDetails {
width
height
}
}Above, our fragment selects a subset of fields available on the MediaItem object type.
The first benefit of defining this fragment, is that we now have a “standard” way of selecting images across our application — whenever we encounter an object with a MediaItem field, we can use the fragment name, rather than selection the fields we want over-and-over again.
query LatestPosts {
posts(first: 10) {
nodes {
title
uri
featuredImage {
...ResponsiveImage
}
}
}
}The second benefit of defining this fragment, is that since our development tooling turns all fragments into TypeScript types, we can use the fragment when declaring component props.
import { ResponsiveImageFragment } from "@types/graphql"
type Props = {
image: ResponsiveImageFragment
}
export function ResponsiveImage(props: Props) {
return <img src={props.image.mediaItemUrl} srcSet={props.image.srcSet} title={props.image.caption} />
}
// Elsewhere...
<ResponsiveImage image={post.featureImage} />Cards and Tiles
It’s highly recommended that when building a site which uses custom post types, listing pages, and post type tiles, that you create a fragment for each object type, along with a component for rendering a tile of that type.