Alt Text

Welcome to part-7 of the series.

As told in the earlier post, this series is based on the learning from this awesome udemy course by John Smilga

In this part we will start optimizing the background images in our site. Right now we have only one big background image in the home page. For this we will use the gatsby-background-image plugin. The doc for the same is here.

So, let’s stop our gatsby develop and npm install the plugin.

npm installnpm install

Next, start the development server by gatsby develop. After that head over to your code editor and create a new file StyledHero.js inside it.

StyledHeroStyledHero

Put the below content in the file. We are making StyledHero.js a general purpose component, which can be used in all pages for the large hero image. All of the code for the component is taken from the docs of the gatsby-background-image plugin.

StyledHeroStyledHero

We are using one additional props in our component, which is home. Our home page will also contain a linear gradient and also the size of the image will also cover the entire page.

We took both of them from the existing layout.css, which is been used in the SimpleHero.js component.

layout.csslayout.css

Now let’s rendered our StyledHero in our Home page. Move over to index.js and replace the SimpleHero with StyledHero.

StyledHeroStyledHero

Next, we will create our query for displaying image in GraphiQL.

GraphiQLGraphiQL

Earlier we used StaticQuery but we will be using PageQuery because index.js is a page. Here, we are using the query which we had created in our GraphiQL. After that passing it as props to our StyledHero component.

index.jsindex.js

Now, when we check in the browser we can see our optimized background image.

Optimized backgroundOptimized background

Next, we will add background image to all pages. First, we will add in the places.js file. Everything will be similar to index.js , except that we are not passing the home prop in StyledHero.

places.jsplaces.js

By not passing the home prop, we get a smaller image with no linear gradient.

PlacesPlaces

Next, we will update the contact.js page. Here we are using a different image.

contact.jscontact.js

It will result in the below change in our Contact page in browser.

Contact PageContact Page

Next, we will update the blog.js file. Here also we are using a different image.

blog.jsblog.js

And our Blog page looks like below in browser.

Blog pageBlog page

This completes part-7 of the series. You can find the code for the same in this link.

As i pushed my code to github, it also did an automatic deployment to netlify which we did in part-5.

So, you can also find the updated site on https://amazinghampi.netlify.com/

This post is also available on DEV.