- Published on
Handling static images in Gatsby
- Authors
- Name
- Petr Siegl
- Mastodon
- @petrsiegl
There are few ways to render static images in Gatsby.
The simplest way is to import the image and use img
tag. But this doesn't optimize the image.
import logoSrc from "../images/logo.png";
<img src={logoSrc}></img>
To optimize the image you can use StaticImage
instead.
import { StaticImage } from "gatsby-plugin-image";
// ...
<StaticImage src="../images/logo.png" ></StaticImage>
When you need to pass the src
attribute dynamically, e.g. using props for a component, you must use query and GatsbyImage
instead. StaticImage
doesn't support dynamic src
attribute.
import { GatsbyImage, getImage } from "gatsby-plugin-image";
import { graphql, useStaticQuery } from "gatsby";
const Main = () => {
const data = useStaticQuery(graphql`
query {
file(relativePath: { eq: "images/logo.png" }) {
childImageSharp {
gatsbyImageData
}
}
}
`);
const image = getImage(data.file)
return (
<Example image={image} />
)
}
const Example = ({image}) => <GatsbyImage image={image} />