After reviewing the link you shared in your comment, it's evident that there are several ways to incorporate images/assets with gatsby:
- Retrieve the image using
graphql
import
the image and get its path
- Place the image in the
static
directory
Getting Started
Assuming you have a component structured like this:
// src/pages/sample.js
import React from 'react'
import { css } from '@emotion/core'
export default () => <div css={css`
width: 10rem;
height: 10rem;
background: url( ... );
`} />
Query Method
PublicURL
If you're utilizing any of the default starters, chances are your src/images
folder is configured with gatsby-source-file-system
, allowing Gatsby to recognize your images. Assuming you know the file name, you can query it as shown below:
{
// ⇣ `base` refers to the file name along with its extension.
file (base: { eq: "image.png" }) {
publicURL
}
}
By querying for the field publicURL
, you'll receive the file's path:
export default ({ data }) => <div css={css`
width: 10rem;
height: 10rem;
background: url(${data.file ? data.file.publicURL : 'your/fallback.png'});
`} />
export const query = graphql`
query {
file(base: { eq: "image.png" }) {
publicURL
}
}
`
ImageSharp
Gatsby typically includes sharp
, enabling image transformations and more. For instance, you can resize an image to 200px width through the following query:
export const query = graphql`
query {
file(base: { eq: "image.png" }) {
childImageSharp {
fixed(width: 200) {
src
}
}
}
}
`
The result can be accessed at
data.file.childImageSharp.fixed.src
.
Importing Images
Leverage webpack for this purpose:
import myImagePath from '../relative/path/to/image.png';
export default () => <div css={css`
width: 10rem;
height: 10rem;
background: url(${myImagePath});
`} />
Moving Images to static
Directory
Create a folder named static
in your root directory if it doesn't already exist. Proceed to transfer your image into it:
root
|--src
`--static
`--image.png
All files within static will be directly copied during build, thus allowing you to reference the image like so:
export default () => <div css={css`
width: 10rem;
height: 10rem;
background: url(/image.png);
`} />
If you're utilizing pathPrefix
in gatsby-config.js
, import withPrefix
from gatsby
and wrap it around the image path.
For a visual demonstration of the first two methods, check out this codesandbox.
We hope this information proves helpful!