Gatsby Contentful Markdown

  

Compare historical build times of Gatsby example sites built on Gatsby Cloud, with data sourced from popular CMS (Content Management System) providers. Get all of Hollywood.com's best Movies lists, news, and more. We work together to form an amazing collective brain SSW is made up of a great team of staff that are passionate about technology and how it meets business needs - including experts in Angular, React, Azure, Azure DevOps (was TFS), SharePoint, Office 365,.NET, WebAPI, Dynamics 365, SQL Server, UX/Design and much more! Gatsby-remark-highlight-code Used for highlighting code syntax; gatsby-source-contentful Used for getting data from Contentful; gatsby-transformer-remark Used for transforming markdown into HTML; A full list of their plugins can be found here. As Gatsby is built on top of React which means extending your website's functionality is easy.

July 3rd, 2019

Hiya!

It's Arisa, a Full-Stack & Frontend Developer living in Germany.

I released this website about a month ago. (Powered by Contentful, Gatsby and Netlify.)

You will find in my first Japanese blog article says I faced a problem.

'Couldn't get thumbnail images and excerpt from Contentful with GraphQl in Gatsby.'

Coinsidentally, or really luckily, I got a comment on my tweet from one evangelist working in Contentful. 😳

He said a really helpful clue.

'Isn't it a Content Model structure problem?'

And I realized the problem was just because I was putting everything in one field💡

I was totally believing in a way I knew from the simple Gatsby web app with Markdown.

Without CMS or like content infrastructure, Gatsby's web app has the data queries.

I believed there must be already prepared data queries in a gatsby-source-contentful plugin🤦‍♀️

Once I realized that better to separete fields for each contents, everything was so easy.

Let's break it down for those of you lookig for the way to get images or excerpts or any other fields from Contentful with Gatsby.

It works with any kind of web apps with Contentful with Gatsby.

As an example, I'll talk about a blog.

Normally, blog has 2 different page structures.

One is with all articles listed up with a loop and the other page is a single article page.

Both of them will look attractive if they have nice top images to tell stories about the topics in each article.

Let's set up an image field first in your Content Model.

Login to your Contentful dashboard, then go to `Content Model` from the header menu.

At this point, I expect you already have a Content Model created.

If not, just create by the buttun in the top right corner says `add content type.`

Select your Content Model, and click `Add a field` in the right side.

Gatsby Contentful Markdown Summary

We want to have a top image for each article then we choose a `Media` as a new field.

You can name this top image field as you like.

The name you saved in this field will be the name of the data query you'll be seeing in a GraphQl later.

Spring boot apache web server download. Now, you have your new top image field for every articles.

Let's check it out the field is added.

Go to `Content` from the header menu, and select the article if you already have one.

If you don't, just create one from there.

I bet you see your new top image field in the article editing page.

Mine has `required` alert but it's because I set this field as a required field to publish articles.

(There is a reason you must know but I'll explain later.)

Upload an image from `Create new asset and link.`

If you want to use the image you already uploaded before, choose `Link existing asset.`

Publish the article but you can't see the image from your article from the browser yet.

You need to get the data query with GraphQl.

Run your blog web app in the terminal.

It shows you the local host and the GraphQl playground.

(* You need to link your Gatsby web app with Contentful before. To do so, check out gatsby-source-contentful docs in below.)

Open your GraphQl playground and take a look at the query from `allContentful{your_content_model_name}.`

Gatsby Contentful Markdown

In mycase, I have `BlogPost` as my Content Model name.

And my image field name is `topImage.`

Open `Docs` in your GraphQl playground.

Follow the queries from `allContentful{your_content_model_name}` > `edges` > `node` > `{your_image_field_name}.`

There you go!

We succeed to find the top image field we just created in a Contentful dashboard.

But you can't get your uploaded image yet.

GraphQl yells at you {your_image_field_name} still has queries to specify.

Wht do we need to get more?

There are a few choices you can make depends on your preference but I'll go for `resize` this time as I personally think the most useful option for images.

The reason behind in here is because, you can get the benefit from Images API from Contentful.

It's amazing and you can output your images without facing an issue with gatsby-image!

Means, you can write with simple JSX.

(I love Gatsby but the image is the thing I always need a bit time to figure out..)

When you use `resize` query from Images API in Contentful, you'll get desired width and height, also, you can change the resizing behavior too! ✨

Imagine that you have an image not fitting in the area and both sides are just blank and only the height is fitting or opposite case.

I feel I want to crop and make it looks fit somehow but I don't want to do that image cropping everytime by myself.

Then just set `resize` with arguments `width` and `height`!

You'll find allowed arguments from GraphQl playground Docs.

When you set the width and height arguments with `resize`, Images API will assign automatically `fit property` as well ✨

I love this fit property from Contentful Images API :)

It will fit automatically in a center of the image and crop the unecessary parts of the images ✂️

How I can check tat out before even seeing in the browser?

I see that already from the GraphQl playground like this.

See closer the place I marked.

And check the docs from Contentful Images API.

You see fit property has fill as a value and w stands for the width you set from the argument width.

Height is also the same.

Just getting the data query resize and set the width and heght arguments, Contentful Images API shapes your images in perfect size ✨

Now, you learned why I chose resize in here.

Then choose `src` to get the images path so that your Gatsby app can output with JSX.

You can write your query into your blog page something like this.

After you save, check out in the browser.

Woohoo! 🎉

You got the image from Content Model field!

Perhaps, if you already had a few articles ready in your Contentful, you might faced this issue.

You made sure your image is uploaded and you got the right queries in GraphQl playground but keep getting 'TypeError: Cannot read property ‘x’ of null.'

Gatsby Contentful Markdown

You might think it's not a query issue and API.

That's right, this error message says, 'Your parent property is still null.'

Which means, before map method is null.

The most simple answer is, you haven't yet uploaded all images in your existing articles 💡

That's why I wrote earlier, there is a reason why I made top image field as required field to publish articles.

Gatsby Contentful Markdown Meaning

If you make this field empty, you'll get the error says 'TypeError: Cannot read property ‘x’ of null.'

Just keep in your mind if you get this error 📝

Hope you know now how Contentful Images API is making your life so much easier!

If you want to see visually how it works in 20 minutes or so, there is an official tutorial from Contentful as well.

You'll get a better image of how resize and fir property works beautifully 😌 (It's not Gatsby but still you get what we can do the same thing in Gatsby)

Also, not only the images.

Gatsby Contentful Starter

You can create fields in any other contents like excerpt to show the beginning or summary of the articles, tags to category your articles etc.

Happy coding 💻!

Tschüs

Gatsby is a static site generator based on React with much popularity nowadays.

Gatsby Contentful Markdown Quotes

The list of sites powered by Gatsby is awe-inspiring:

  • My website 😂
Contentful cms

One of its most definite advantages is the ability to obtain content from many different sources:

  • Wordpress API
  • Contentful
  • Markdown files

In this article, we will focus on the last one to build a page with separated sections organized by folders containing the different types of posts (blog, projects, and talks).

Files hierarchy

Contentful Cms

Configuration

To fetch data from the file system, we need to use a plugin called gatsby-source-filesystem.

After fetching the data, we need to convert the Markdown to valid HTML. For that, we are going to use gatsby-transformer-remark.

After installing the packages with npm or yarn, the next step is to configure Gatsby to read from each one of the content folders and parse the Markdown files:

Templates

For each section, we want to define a template for the posts list and optionally one for the post detail (the links for the talks and projects are external, so only the blog has detail page).

List page example

Let’s analyze what’s happening here:

  1. We query all the Markdown content, filtering by collection (blog).
  2. We also filter by published state. That way, we can include a flag in the frontmatter to mark the file as “unpublished.”
  3. We add pagination ability. We are going to generate proper information later.
  4. We pass the edges of the data, as well as the pagination information to a “functional” component, which renders the information correctly.

Detail page example

This case is even simpler, as there is no pagination or collection type involved. The query receives a slug as parameter. The data is passed then to a functional component.

Pages generation

Now, we need to update gatsby-node.js, to read for the separated content files in the proper directories.

To maintain our file clean, we are going to create a folder called gatsby, with two files inside: create-pages.js and on-create-node.js.

gatsby-node.js

on-create-node.js

With this hook, we are telling Gatsby to add two new fields when the node is created. We can access those fields later with GraphQL, to filter the pages by collection and to obtain the detail for a determined slug (which includes the collection).

create-pages.js

Let’s analyze what’s happening in this hook:

  1. We query all the Markdown content, excluding the unpublished items.
  2. For each type of content, we run a collection generator, which filters the content by type and creates the proper pages using the templates.

Gatsby Source Contentful

Note that we can define for each collection:

  • How many items we want to display in each page
  • If the collection must render individual detail pages

Real example

As I said previously, I’ve used this technique to build this page, so feel free to inspect the files to see a complete example.