Gatsby
Up and Running with Gatsby: Images

Using an Image in the Index Page

PRO

Let's use our image query in the index page.

We can now use the query we built in the last video inside of our page query in index.js. We can also replace eveyrthing inside fluid with a GraphQL fragment (a partial query) called GatsbyImageSharpFluid. The final page query will look like this:

export const query = graphql`
  query {
    site {
      siteMetadata {
        title
      }
    }
    file(relativePath: { eq: "images/lodge.jpg" }) {
      childImageSharp {
        fluid {
          ...GatsbyImageSharpFluid
        }
      }
    }
  }
`

Now, we can use use Gatsby Image in our LodgeImage component. First, import Gatsby Image:

import Image from "gatsby-image"

Then, update the LodgeImage component with this:

const LodgeImage = styled(Image)`
  max-width: 400px;
    margin-top: 20px;
    border-radius: 10px;
`

Finally, in the exported component where we use the LodgeImage component, replace src with fluid like so:

// src/pages/index.js
export default ({ data }) => (
  <Layout>
    <LodgeImage fluid={data.file.childImageSharp.fluid} alt="Lodge" />
    <p>Welcome to {data.site.siteMetadata.title}!</p>
  </Layout>
)

That's it! If you run gatsby develop and visit the site, you should see a nice blurred placeholder as the page loads.

Let's do an assignment in the next video to get some practice adding images to pages.