Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(gatsby-source-contentful): LongText fields require markdown transformer #20398

Merged
merged 9 commits into from
Jan 15, 2020
32 changes: 26 additions & 6 deletions packages/gatsby-source-contentful/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -237,24 +237,44 @@ You might query for a **single** node inside a component in your `src/components

#### A note about LongText fields

If you include fields with a `LongText` type in your Contentful `ContentType`, their returned value will be **an object not a string**. This is because Contentful LongText fields are Markdown by default. In order to handle the Markdown content properly, this field type is created as a child node so Gatsby can transform it to HTML.
On Contentful, a "Long text" field uses Markdown by default. The field is exposed as an object, while the raw Markdown is exposed as a child node. Except if the content is Markdown-free, you cannot use it as is:

`ShortText` type fields will be returned as strings.
```graphql
{
contentfulCaseStudy {
body {
body
}
}
}
```

Querying a **single** `CaseStudy` node with the ShortText properties `title` and `subtitle` and LongText property `body` requires formatting the LongText fields as an object with the _child node containing the exact same field name as the parent_:
In order to handle the Markdown content, you must use a transformer plugin such as [gatsby-transformer-remark](https://www.gatsbyjs.org/packages/gatsby-transformer-remark/). The transformer will create a childMarkdownRemark on the "Long text" field and expose the generated html as a child node:

```graphql
{
contentfulCaseStudy {
title
subtitle
body {
body
childMarkdownRemark {
html
}
}
}
}
```

You can then insert the HTML inline in your JSX:

```
<div
className="body"
dangerouslySetInnerHTML={{
__html: data.contentfulCaseStudy.body.childMarkdownRemark.html,
}}
/>
```
While this solution is not ideal, you can alternatively use "Rich text" fields instead of "Long text" in order to avoid the inline html (see below).

#### Duplicated entries

When Contentful pulls the data, all localizations will be pulled. Therefore, if you have a localization active, it will duplicate the entries. Narrow the search by filtering the query with `node_locale` filter:
Expand Down