This appendix provides a comprehensive account of the APIs for Gatsby’s built-in <Link />
and image components.
The Gatsby <Link />
component is used in Gatsby applications to power linking between internal pages generated by Gatsby and to enable preloading of resources on other pages such that when the link is clicked, the change is instantaneous.
The Gatsby <Link>
component should only be used for internal (not external) links. For more information about how to handle situations where a link’s internal or external target is uncertain, consult the Gatsby documentation’s guide to relative links.
When the <Link />
component is visible within the browser viewport, Gatsby uses an IntersectionObserver
to perform a low-priority fetch. When an onMouseOver
event on the <Link />
component occurs, this triggers a high-priority fetch as it is likely the user is about to navigate to that resource.
At its core, the <Link />
component is a wrapper around the Link
component provided by @reach/router
with Gatsby-specific enhancements, and all props provided are also passed to @reach/router
’s Link
component.
Gatsby uses the withPrefix
helper function to construct pathnames that respect configured path prefixes in uses of the <Link />
component or the navigate
function (see ““navigate””).
You should use the <Link />
component as a replacement for HTML <a>
tags that represent links between pages in the same Gatsby site. However, you should still use HTML <a>
tags for all links that reference pages that are external to Gatsby, as seen in the following example:
import
React
from
"react"
import
{
Link
}
from
"gatsby"
const
Page
=
()
=>
(
<
div
>
<
p
>
Check
out
my
<
Link
to
=
"/blog"
>
blog
<
/Link>!
<
/p>
<
p
>
{
/* Note that external links still use `a` tags. */
}
Follow
me
on
<
a
href
=
"https://twitter.com/gatsbyjs"
>
<
/a>!
<
/p>
<
/div>
)
For an Egghead.io video tutorial demonstrating this example, see “Why and How to Use Gatsby’s Link Component” by Jason Lengstorf.
To apply an active state to a Gatsby <Link />
component that indicates it is representative of the page the user is currently viewing, you can use one of two props:
activeStyle
, which is a style object that will only be applied when the current link item is active
activeClassName
, which is a class name that will only be added when the current item is active
This is illustrated in the following example:
import
React
from
"react"
import
{
Link
}
from
"gatsby"
const
SiteNavigation
=
()
=>
(
<
nav
>
<
Link
to
=
"/"
{
/* This assumes the `active` class is defined in your CSS */
}
activeClassName
=
"active"
>
Home
<
/Link>
<
Link
to
=
"/about/"
activeStyle
=
{{
color
:
"red"
}}
>
About
<
/Link>
<
/nav>
)
For an Egghead.io video tutorial demonstrating this, see “Add Custom Styles to the Active Link Using Gatsby’s Link Component” by Jason Lengstorf.
Sometimes, you may need to indicate a <Link />
as active even if its path only partially matches the current URL. By default, the activeStyle
and activeClassName
props will only be set on a given <Link />
component if there is an exact match between the path and the current URL. However, you may need to represent multilevel or other menus where, say, a <Link />
component pointing to /blog also needs to be active for /blog/lorem-ipsum.
In this case, use the partiallyActive
prop to indicate that a partial match rather than an exact match should use the given activeStyle
or activeClassName
prop. This is illustrated in the following example:
import
React
from
"react"
import
{
Link
}
from
"gatsby"
const
Header
=
<>
<
Link
to
=
"/articles/"
activeStyle
=
{{
color
:
"red"
}}
partiallyActive
=
{
true
}
>
Articles
<
/Link>
<
/>;
The partiallyActive
prop is only available on the Gatsby <Link />
component as of Gatsby 2.1.31.
There are three ways that Gatsby allows you to work with props in the context of the <Link />
component:
The getProps
prop is useful for advanced styling.
The state
prop allows you to pass state as props to the linked page.
The replace
prop allows you to modify the Back button’s behavior.
The getProps
prop can be used on any <Link />
component and will yield an object that contains the following properties:
isCurrent
, which is set to true
if the location.pathname
is identical to the <Link />
component’s to
prop value
isPartiallyCurrent
, which is set to true
if the location.pathname
begins with the <Link />
component’s to
prop value
href
, which is the value of the to
prop
location
, which represents the page’s location
object
For more information about the getProps
prop, consult @reach/router
’s documentation on its Link API.
The state
prop is used when you wish to pass data from the source page to the destination page of a <Link />
component. This is done by passing a state
prop to the <Link />
component, or during an invocation of the navigate
helper function. The destination page will have a location
prop containing a nested state
object whose structure represents the passed data.
Consult the following example from the Gatsby documentation:
const
PhotoFeedItem
=
({
id
})
=>
(
<
div
>
<
Link
to
=
{
`/photos/
${
id
}
`
}
state
=
{{
fromFeed
:
true
}}
>
View
Photo
<
/Link>
<
/div>
)
const
Photo
=
({
location
,
photoId
})
=>
{
if
(
location
.
state
.
fromFeed
)
{
return
<
FromFeedPhoto
id
=
{
photoId
}
/>
}
else
{
return
<
Photo
id
=
{
photoId
}
/>
}
}
For more information about the state
prop, consult the Egghead.io tutorial video “Include Information About State in Navigation with Gatsby’s Link Component” by Jason Lengstorf.
The replace
prop is used to modify the Back button’s behavior. In one of the most common cases, you can use it to ensure that the current page, which may be a page you do not want the user to be able to navigate back to using the Back button (such as a confirmation page), is not saved in the browser history. You can use the replace
prop to substitute the current page’s URL in the browser history with the destination of the <Link />
, as seen in the following example:
import
React
from
"react"
import
{
Link
}
from
"gatsby"
const
AreYouSureLink
=
()
=>
(
<
Link
to
=
"/confirmation/"
replace
>
Yes
,
I
’
m
sure
<
/Link>
)
For more information about the replace
prop, consult the Egghead.io tutorial video “Replace Navigation History Items with Gatsby’s Link Component” by Jason Lengstorf.
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
GatsbyImage
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
.
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. |
A comprehensive list of all options available to the Image plugin can be found in the Gatsby documentation.
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.
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
}
/>
}
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.
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.
Prop | Type | Description |
---|---|---|
image (required) |
GatsbyImageData |
The image data object, returned from the gatsbyImageData resolver |
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.
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.
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 |
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).
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) } }
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.
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.
There are several advanced options that you can pass to control the cropping and resizing behavior. For more details, see ““transformOptions””.
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.
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. |
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.
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.
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. |
For more information about trim
, cropFocus
, and fit
, consult the Sharp documentation.
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.
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
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
}
/>
Use the getSrcSet
function to get the default image srcset
. This will be the fallback, so usually jpg
or png
.
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
.
For more information about this helper function and how to use it with CSS media queries, consult the Gatsby documentation’s section on withArtDirection
.
3.134.102.182