Appendix B. Gatsby Component APIs

This appendix provides a comprehensive account of the APIs for Gatsby’s built-in <Link /> and image components.

gatsby-plugin-image

The Gatsby Image plugin includes two components to display responsive images in your site, one for static images and the other for dynamic images:

StaticImage
Use this if the image is the same every time the component is used (e.g., a site logo or index page hero image).
GatsbyImage
Use this if the image is passed in to the component as a prop, or otherwise changes (e.g., a blog post hero image or author avatar).

We’ll look at these in turn in the following sections, but first Table B-2 lists the shared props that can be passed to both components. These props are all optional, with the exception of alt.

Table B-2. Props accepted by the StaticImage and GatsbyImage components
Prop Type Default Description
alt (required) string Alternative text, passed to the <img> tag. Required for accessibility.
as ElementType "div" The HTML element used for the outer wrapper.
loading "eager" or "lazy" "lazy" Loading behavior for the image. You should set this to "eager" for above-the-fold images to ensure they start loading before React hydration.
className string The CSS class applied to the outer wrapper.
imgClassName string The CSS class applied to the <img> element.
style CSSProperties Inline styles applied to the outer wrapper.
imgStyle CSSProperties Inline styles applied to the <img> element.
backgroundColor string transparent The background color applied to the wrapper.
objectFit object-fit property cover Resizing behavior for the image within its container.
objectPosition object-position property 50% 50% The position of the image within its container.
Note

A comprehensive list of all options available to the Image plugin can be found in the Gatsby documentation.

StaticImage

The StaticImage component can take all the image options described in “Image Options” as props, as well as all the shared props listed in Table B-2. It also takes one additional required prop, listed in Table B-3.

Table B-3. Additional props required by StaticImage
Prop Type Description
src (required) string The source image, processed at build time; can be a path relative to the source file, or an absolute URL

The images are loaded and processed at build time, so there are restrictions on how you pass props to the component. The values need to be statically analyzed at build time, which means you can’t pass them as props from outside the component, or use the results of function calls, for example. You can either use static values, or use variables within the component’s local scope:

export function Dino() {
  // Local variables are fine
  const width = 300
  return <StaticImage src="trex.png" width={width} />
}

If you find yourself wishing you could use a prop for the image src, then it’s likely that you should be using a dynamic image:

// A variable in the same file is fine
const width = 300
export function Dino() {
  // This works because the value can be statically analyzed
  const height = (width * 16) / 9
  return <StaticImage src="trex.png" width={width} height={height} />
}
Note

The StaticImage component does not support higher-order components, which includes the styled function from libraries such as Emotion and Styled Components. The parser relies on being able to identify StaticImage components in the source, and passing them to a function means this is not possible. For more information about this limitation, consult the Gatsby documentation’s section on using StaticImage with CSS-in-JavaScript libraries.

GatsbyImage

This component accepts all the shared props listed in Table B-2, as well as the one in Table B-4. These props are passed directly to the component, and are not to be confused with image options, which are passed to the GraphQL resolver when using dynamic images.

Table B-4. Additional props required by GatsbyImage
Prop Type Description
image (required) GatsbyImageData The image data object, returned from the gatsbyImageData resolver

Image Options

There are a few differences in how you specify options for StaticImage and GatsbyImage:

  • When using StaticImage, options are passed as props to the component, whereas for the GatsbyImage component they are passed to the gatsbyImageData GraphQL resolver.

  • In the StaticImage component, props such as layout and placeholder take a string, while the resolver takes a GraphQL enum, which is uppercase by convention and is not quoted like a string. Both syntaxes are shown in the following table.

Warning

For dynamic images, these options are for the gatsbyImageData resolver on sharp nodes. If you are using gatsbyImageData from a different plugin, such as a CMS or image host, you should refer to that plugin’s documentation for the options, as they will differ. Static images use sharp under the hood, so these options apply when using the StaticImage component too.

Table B-5 lists the options available to both static and dynamic images. We’ll look at these in more detail in the following sections.

Table B-5. Image options
Option Default string/enum value Description
layout "constrained" or CONSTRAINED Determines the size of the image and its resizing behavior
aspectRatio Source image aspect ratio Forces a specific ratio between the image’s width and height
width/height Source image size Changes the size of the image
placeholder "dominantColor" or DOMINANT_COLOR Sets the style of temporary image shown while the full image loads
formats ["auto","webp"] or [AUTO,WEBP] File formats of the images generated
transformOptions {fit: "cover", cropFocus: "attention"} or {fit: COVER, cropFocus: ATTENTION} Options to pass to sharp to control cropping and other image manipulations

layout

The image components support three types of layout, which determine the image sizes that are generated, as well as the resizing behavior of the image itself in the browser (see Table B-6).

Table B-6. layout options for StaticImage and DynamicImage
Layout Component prop value Resolver prop value Description
Constrained "constrained" CONSTRAINED This is the default layout. It displays the image at the size of the source image, or you can set a maximum size by passing in width or height. If the screen or container size is less than the width of the image, the component scales it down to fit, maintaining its aspect ratio. The component generates smaller versions of the image so that a mobile browser doesn’t need to load the full-size image.
Fixed "fixed" FIXED Use this for fixed-size images. The image will always display at the same size, and will not shrink to fit its container. The size is either the size of the source image, or the size set by the width and height props. Only use this if you are certain that the container will never need to be narrower than the image.
Full width "fullWidth" FULL_WIDTH Use this for images that are always displayed at the full width of the screen, such as banners or hero images. Like with the constrained layout, the image will be resized to fit the container. However, it is not restricted to a maximum size, so will grow to fill the container however large it is, maintaining its aspect ratio. The component generates several smaller image sizes for different screen breakpoints, so that the browser only needs to load one large enough to fit the screen. You can pass a breakpoints prop if you want to specify the sizes to use, though in most cases you can allow it to use the default.

To set the layout of a static image, pass in the type to the layout prop:

<StaticImage
  src="./dino.png"
  alt="A dinosaur"
  layout="fixed"
/>

For a dynamic image, pass it to the resolver:

dino {
  childImageSharp {
    gatsbyImageData(layout: FIXED)
  }
}

width and height

The width and height props are available in the fixed and constrained layouts:

  • For a fixed layout, these define the size of the image displayed onscreen.

  • For a constrained image, these define the maximum size, as the image will scale down to fit smaller containers if needed.

Size props are optional in GatsbyImage and StaticImage. Because the images are processed at build time, the plugin knows the size of the source image and can add the correct width and height to the <img> tag, so it displays correctly with no layout jumping. However, if you want to change the display size you can use the size options to do this.

If you set just one of these, the source image is resized to that width or height while maintaining its original aspect ratio. If you include both, then it is also cropped if needed to ensure it is that exact size.

aspectRatio

The aspectRatio prop forces an image to the specified aspect ratio, cropping it if needed. The value is a number, but can be clearer to express as a fraction: e.g., aspectRatio={16/9}. This prop is available in the fixed, constrained, and fullWidth layouts:

  • For fixed and constrained images, you can also optionally pass either width or height, and it will use that to calculate the other dimension. For example, if you pass width={800} aspectRatio={4/3}, then height will be set to the width divided by the aspect ratio: so, 600. Passing 1 as the aspectRatio will crop the image to a square. If you don’t pass a width or height, then it will use the source image’s width.

  • For fullWidth images you don’t specify width or height, as this layout resizes the image to fit the screen width. Passing aspectRatio will crop the image if needed, and the height will scale according to the width of the screen. For example, if you set aspectRatio to 16/9, then when the image is displayed full width on a screen that is 1,280 pixels (px) wide, the image will be 720 px high.

Note

There are several advanced options that you can pass to control the cropping and resizing behavior. For more details, see ““transformOptions””.

placeholder

Gatsby image components are lazy-loaded by default, which means that if they are offscreen they are not loaded by the browser until they come into view. To ensure that the layout does not jump around, a placeholder is displayed before the image loads. You can choose one of three types of placeholder, listed in Table B-7, or not use a placeholder at all.

Table B-7. placeholder values
Placeholder Component prop value Resolver prop value Description
Dominant color "dominantColor" DOMINANT_COLOR The default placeholder. This calculates the dominant color of the source image and uses it as a solid background color.
Blurred "blurred" BLURRED This generates a very low-resolution version of the source image and displays it as a blurred background.
Traced SVG "tracedSVG" TRACED_SVG This generates a simplified, flat SVG version of the source image, which it displays as a placeholder. This works well for images with simple shapes or that include transparency.

formats

The Gatsby Image plugin supports four output formats: JPEG, PNG, WebP, and AVIF. The default component prop value is ["auto", "webp"], and the default resolver prop value is [AUTO, WEBP]; this means that by default the plugin generates images in the same format as the source image, as well as WebP. For example, if your source image is a PNG, it will generate PNG and WebP images.

In most cases, you should not change this. However, in some cases you may need to manually set the formats. One reason for doing so is if you want to enable support for AVIF images. AVIF is a new image format that results in significantly smaller file sizes than alternative formats. It currently has limited browser support, but this is likely to increase. It is safe to include as long as you also generate fallbacks for other browsers, which the Image plugin does automatically by default.

transformOptions

The options listed in Table B-8 can be passed in as an object to transformOptions, either as a prop to StaticImage, or to the resolver for dynamic images. They are advanced settings that most people will not need to change. Any provided object is merged with the defaults listed here.

Table B-8. transformOptions options
Option Default Description
grayscale false Converts the image to grayscale.
duotone false Adds a duotone effect. Pass false for no duotone, or an options object containing {highlight: string, shadow: string, opacity: number}.
rotate 0 Rotates the image. The value is provided in degrees.
trim false Trims “boring” pixels.
cropFocus "attention" or ATTENTION Controls crop behavior.
fit "cover" or COVER Controls behavior when resizing an image and providing both width and height.
Note

For more information about trim, cropFocus, and fit, consult the Sharp documentation.

Helper Functions

There are a number of utility functions to help you work with gatsbyImageData objects. Gatsby strongly recommends that you do not try to access the internals of these objects directly, as the format could change; instead, use the functions described in the following sections.

getImage

Use the getImage function to safely get a gatsbyImageData object. It accepts several different sorts of objects and is null-safe, returning undefined if the object passed or any intermediate children are undefined.

If passed a File object, this function will return file?.childImageSharp?.gatsbyImageData. If passed a node such as a ContentfulAsset that includes a gatsbyImageData field, it will return the gatsbyImageData object. If passed a gatsbyImageData object itself, it will return the same object. For example:

import { getImage } from "gatsby-plugin-image"

const image = getImage(data.avatar)
// This is the same as:
const image = data?.avatar?.childImageSharp?.gatsbyImageData

getSrc

Use the getSrc function to get the default image src as a string. This will be the fallback, so usually jpg or png. This function accepts the same types as getImage. For example:

import { getSrc } from "gatsby-plugin-image"

// ...
const src = getSrc(data.hero)
return <meta property="og:image" content={src} />

getSrcSet

Use the getSrcSet function to get the default image srcset. This will be the fallback, so usually jpg or png.

withArtDirection

By default, the Image plugin displays different image resolutions at different screen sizes, but it also supports art direction, which is where a visually different image is displayed at different sizes. Example usages include displaying a simplified logo or a tighter crop on a profile picture when viewing on a small screen. To enable this, you can use the withArtDirection function. You need both images available from GraphQL in the case of a replacement image, and you should be able to write a media query for each size.

The first argument this function takes is the default image. This is displayed when no media queries match, but it is also used to set the layout, size, placeholder and most other options. You then pass an array of art-directed images, which are objects with media and image values:

import { GatsbyImage, getImage, withArtDirection } from "gatsby-plugin-image"

export function MyImage({ data }) {
  const images = withArtDirection(getImage(data.largeImage), [
    {
      media: "(max-width: 1024px)",
      image: getImage(data.smallImage),
    },
  ])

  return <GatsbyImage image={images} />
}

When the screen is less than 1,024 px wide, it will display smallImage. Otherwise, it will display largeImage.

Note

For more information about this helper function and how to use it with CSS media queries, consult the Gatsby documentation’s section on withArtDirection.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.134.102.182