Create a homepage banner

Welcome to the second article in the getting started with Prismic & Gatsby tutorial series. We'll be walking through the steps required to convert the top homepage banner from being hardcoded in your Gatsby app to being filled with content from Prismic.


ūüēô Before Reading

If you haven't already gone through the first step, we recommend you start there to download the project, launch a Prismic repository, and install the required plugin and dependencies.

See the content model

The first step when converting a project to use a headless CMS like Prismic is to model your content. Let's take a quick look at our website to know what we need to do.

Re-launch your site by running npm start. And take a look at your homepage. There's a banner at the top of the page that will keep as a static top-level component.

Look at the content model in Prismic

Now, let's model our banner's static top-level fields. In this example, we will use the following fields:

Here's a video to further show this.

This model has already been put into place for you. In your Prismic repository, click on the Custom Types button in the left-hand navigation bar, and select the Homepage type. Here you can see how these fields were configured in Prismic.

‚ö†ÔłŹ No need to modify the Custom types

You do not need to change anything in the Custom types of your repository. Just take a look at how it is set up. If you wish to change anything, we highly recommend you wait until the end of this step by step tutorial.

The homepage Custom Type

Then, go back, click on the Content button in the left-hand navigation bar and select the Homepage document to view it live. It should look something like this:

The homepage document in Prismic

Now that we have a good understanding of the model let's take a look at how to retrieve your content from Prismic.

1. Test the query

Run the project with npm start, and take a look at your API Explorer at http://localhost:8000/__graphql. Once there, input this GraphQL query in the left-hand panel:

Copy
query Homepage {
  allPrismicHomepage {
    edges {
      node {
        data {
          banner_title {
            raw
          }
          banner_description {
            raw
          }
          banner_link {
            url
            type
            uid
          }
          banner_link_label {
            raw
          }
          banner_background {
            url
            thumbnails
            alt
          }
        }
      }
    }
  }
}

You can run the query by pressing the "play" button ‚Ė∑ at the top, showing you the query results on the right. Read, Anatomy of a query.

2. Render the results

Let's now render the results to produce the homepage banner.

Update the index.js file

Open the file at /src/pages/index.js and paste the following code. You can see we pass the bannerContent results to our <HomepageBanner /> component. Here's what the file should look like:

Copy
import React from 'react'
import { graphql } from 'gatsby'
import Layout from '../components/Layout'
import SEO from '../components/SEO'
import HomepageBanner from '../components/HomepageBanner'
import MainContent from '../components/MainContent'

const Homepage = ({ data }) => {
  if (!data) return null
  const document = data.allPrismicHomepage.edges[0].node.data

  const bannerContent = {
    title: document.banner_title,
    description: document.banner_description,
    link: document.banner_link,
    linkLabel: document.banner_link_label,
    background: document.banner_background,
  }

  return (
    <Layout isHomepage>
      <SEO title="Home" />
      <HomepageBanner bannerContent={bannerContent} />
      <MainContent />
    </Layout>
  )
}

export const query = graphql`
  query Homepage {
    allPrismicHomepage {
      edges {
        node {
          data {
            banner_title {
              raw
            }
            banner_description {
              raw
            }
            banner_link {
              url
              type
              uid
            }
            banner_link_label {
              raw
            }
            banner_background {
              url
              thumbnails
              alt
            }
          }
        }
      }
    }
  }
`

export default Homepage

Update the HomepageBanner component

Open your src/components/HomepageBanner.js file. We will now update this file to retrieve the bannerContent prop that we passed in the index.js file. Replace the static content with the following code. We will use the prismic-reactjs library installed in the last article to help with displaying Rich Text fields.

Copy
import React from 'react'
import { Link } from 'gatsby'
import { RichText } from 'prismic-reactjs'

const HomepageBanner = ({ bannerContent }) => (
  <section
    className="homepage-banner"
    style={{
      backgroundImage: `linear-gradient(rgba(0, 0, 0, 0.4), rgba(0, 0, 0, 0.6)), url(${bannerContent.background.url})`,
    }}
  >
    <div className="banner-content container">
      <h2 className="banner-title">
        {RichText.asText(bannerContent.title.raw)}
      </h2>
      <p className="banner-description">
        {RichText.asText(bannerContent.description.raw)}
      </p>
      <Link to={bannerContent.link.url} className="banner-button">
        {RichText.asText(bannerContent.linkLabel.raw)}
      </Link>
    </div>
  </section>
)

export default HomepageBanner

You can see that we're now populating the homepage banner with our Prismic content. If you want to learn more, check out our articles on Rendering a Rich Text field and Rendering an Image.

Some of you might have noticed that we no longer use the hardcoded Link path: "/about". Link fields are processed using the official Gatsby Link and a linkResolver function from your site's gatsby-config.js. The resolved URL is provided at the url field from the query. If the link type is a web link (i.e., a URL external from your site), the URL is provided without additional processing.

This is a bit more complicated and will require that we set up a Link Resolver function. Let's do that now.

3. Add a Link Resolver

The Link Resolver is a simple function that takes in a Prismic document object or Link field and returns the corresponding URL for that page in your site. Create a file such as src/utils/linkResolver.js and add the following code:

Copy
const linkResolver = (doc) => {
  if (doc.type === 'page') {
    return `/${doc.uid}`
  }
  return '/'
}

module.exports = linkResolver

As you can see here, if the link passed to the Link Resolver is of the type "page", then it will generate the URL using the page's UID value (which we will explore further in a later article). Anything else will return the root of the website: '/'.

Now register it with the plugin. Open the gatsby-config.js file and update the file to this:

Copy
const linkResolver = require('./src/utils/linkResolver')

module.exports = {
  siteMetadata: {
    title: 'Gatsby + Prismic Tutorial',
    description: 'Learn how to integrate Prismic into your Gatsby project.',
  },
  plugins: [
    {
      resolve: 'gatsby-source-prismic',
      options: {
        repositoryName: 'your-repo-name',
        linkResolver: () => (doc) => linkResolver(doc),
        schemas: {
          homepage: require('./custom_types/homepage.json'),
          navigation: require('./custom_types/navigation.json'),
          page: require('./custom_types/page.json'),
        },
      },
    },
    'gatsby-plugin-react-helmet',
    'gatsby-transformer-sharp',
    'gatsby-plugin-sharp',
    {
      resolve: 'gatsby-plugin-manifest',
      options: {
        icon: 'src/images/favicon.png',
      },
    },
    {
      resolve: 'gatsby-source-filesystem',
      options: {
        name: 'images',
        path: `${__dirname}/src/images`,
      },
    },
    {
      resolve: 'gatsby-plugin-google-fonts',
      options: {
        fonts: [`Lato\:400,400,700,700i,900`, `Amiri\:400,400,700,700i`],
      },
    },
  ],
}

‚ö†ÔłŹ Update the repositoryName

Make sure that you update the repositoryName to match the URL of the Prismic repository created earlier in this article. To find this, go to your Prismic dashboard, then to your repository.

If the URL for your repository is https://my-awesome-repository.prismic.io, you'll need to replace 'your-repo-name' above with 'my-awesome-repository'.

Congrats, now the homepage banner is filled with content pulled from Prismic!

4. Test the new content

To test that the content is coming from Prismic, do the following:

  1. Go to your Prismic repository and open the homepage document.
  2. Make a change to your banner content.
  3. Save and publish your changes.
  4. In your terminal, stop the current Gatsby server by pressing CTRL + C.
  5. Relaunch your server by running npm start.

This will re-build your site and update the content from your Prismic repository. When the build is complete, you can refresh the homepage and should see your updated content.

Next steps

Next up, we will be replacing the rest of the homepage with Prismic content using Slices.

Converting the Homepage main content (slices) ‚Üí