Gatsby
Up and Running with Gatsby: Images
  •  

Importing Images

PRO
Outline

There are a few different ways to use images in Gatsby.

The first is to just import them into components. Gatsby already has the Webpack build set up to support this. For example in index.js, we can just do the following:

import lodge from "../images/lodge.jpg"

In the video, we use styled-components to add this image to the page by creating a LodgeImage component:

const LodgeImage = styled.img`
  max-width: 400px;
    margin-top: 20px;
    border-radius: 10px;
`

We can then use that component inside of the Layout component:

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

You should be able to see the image when you run gatsby develop and go to localhost:8000.

Importing images directly is one way to use images in Gatsby. Gatsby also provides an "escape hatch" for using images or other static files outside of the build process. Let's learn about that in the next video.

 

I finished! On to the next chapter