Gatsby.js — Static Assets

John Au-Yeung
3 min readFeb 6, 2021
Photo by Austin Distel on Unsplash

Gatsby is a static web site framework that’s based on React.

We can use it to create static websites from external data sources and more.

In this article, we’ll look at how to create a site with Gatsby.

Importing Assets Directly into Files

We can import images directly into component files.

For example, we can write:

import React from "react"
import laptop from "../images/laptop.jpg"
const IndexPage = () => {
return (
<div>
<img src={laptop} alt="laptop" />
</div >
)
}
export default IndexPage

We import the src/images/laptop.jpg file as a module.

Then we pass that directly as the value of the src prop of our img element.

And it’ll be displayed as an image.

We can also add images with CSS:

src/pages/index.css

.laptop {
background-image: url(../images/laptop.jpg);
height: 200px;
width: 200px;
}

src/pages/index.js

import React from "react"
import './index.css'
const IndexPage = () => {
return (
<div className='laptop'>
</div >
)
}
export default IndexPage

--

--