Gatsbyjs Working with images
Let's say we have an image called 1.jpg located in our folder called "assets". We would normally display it using
Easy enough.
Why do you want to use gatsby image sharp plugin, that's because we want to 'size' our image for different screen resolution settings. For example, you might want to target mobile devices or desktop, you don't have to create multiple images.
Now if you work with Gatsby, normally we use graphql. First we need to install a plugin called "gatsby-source-filesystem".
resolve: "gatsby-source-filesystem",
options: {
name: "assets",
path: `${__dirname}/static/assets/`
}
Our image reside in this folder "static/assets". If you have a 1.jpg in here, go to http://localhost:8000/___graphql
Paste the following code :-
query {
imageMain: file(relativePath: {eq: "1.jpg"}) {
childImageSharp {
fluid(maxWidth: 1000) {
base64
tracedSVG
aspectRatio
src
srcSet
srcWebp
srcSetWebp
sizes
originalImg
originalName
}
}
}
}
We are asking a gatsby plugin called gatsby-plugin-sharp which allow us to optimized image. Generally, we would be able to use fixed or fluid image.
To display the image on our page, we need to create a page and it construct a graphql based on code above and display it using Gatsby's Img component. (This is exactly how we would do it using img).
The code are as follows :-
import React from 'react'
import { Link, graphql } from 'gatsby'
import Img from 'gatsby-image'
const IndexPage = (props) => (
<div>
<h1>Hi people</h1>
<p>Welcome to your new Gatsby site.</p>
<p>Now go build something great.</p>
<Link to="/page-2/">Go to page 2</Link>
<Img fluid={props.data.imageMain.childImageSharp.fluid} />
</div>
)
export default IndexPage
export const pageQuery = graphql`
query {
imageMain: file(relativePath: {eq: "1.jpg"}) {
childImageSharp {
fluid(maxWidth: 1000) {
base64
tracedSVG
aspectRatio
src
srcSet
srcWebp
srcSetWebp
sizes
originalImg
originalName
}
}
}
}
`;
If you would like to play around with fixed image, you can potentially used the following code
import React from 'react'
import { Link, graphql } from 'gatsby'
import Img from 'gatsby-image'
const IndexPage = (props) => (
<div>
<h1>Hi people</h1>
<p>Welcome to your new Gatsby site.</p>
<p>Now go build something great.</p>
<Link to="/page-2/">Go to page 2</Link>
<Img fixed={props.data.imageMain.childImageSharp.fixed} width="1000" />
</div>
)
export default IndexPage
export const pageQuery = graphql`
query {
imageMain: file(relativePath: {eq: "1.jpg"}) {
childImageSharp {
fixed(width: 1000) {
base64
tracedSVG
aspectRatio
src
width
height
}
}
}
}
`;
Noticed, width and require are required properties.
Comments