larpo
larpo

Reputation: 1163

Render markdown/HTML from frontmatter in a Gatsby NetlifyCMS project

NetlifyCMS offers a markdown editor that allows the insertion of markdown (and code blocks) within frontmatter.

The resulting markdown file might have content like:

---
featureSubtitle: |-
  ![fdsaf](/img/cdc-w9keokhajkw-unsplash.jpg "blah")

  # Markdown H1

  ## Markdown H2


  <h1>Test</h1>
  <p>Paragraph</p>
---

This is then loaded onto the page from frontmatter via a graphql query like:

export const pageQuery = graphql`
  query FeaturePageByID($id: String!) {
    markdownRemark(id: { eq: $id }) {
      id
      html
      frontmatter {
        title
        description
        featureSubtitle
      }
    }
  }
`;

and

{featureSubtitle && featureSubtitle ? (
                  <div
                    dangerouslySetInnerHTML={{ __html: featureSubtitle }}
                  />
                ) : null}

This however appears to render the HTML correctly, but not the markdown.

enter image description here

Upvotes: 1

Views: 2164

Answers (1)

A. van Hugten
A. van Hugten

Reputation: 823

The gatsby transformer remark plugin does convert markdown to html in the body of your markdown file and gets the frontmatter data at the top of your markdown file. The frontmatter is used mainly for metadata. You can however convert the frontmatter field yourself to html. See this link.

Or make sure you use the body for the markdown field like this in your config.yml for netlify cms:

fields:
      - { label: "featureSubtitle", name: "body", widget: "markdown" }

Then it can be retrieved as html with the html field in your graphql query and be used like this:

<div dangerouslySetInnerHTML={{ __html: html}} />

Upvotes: 2

Related Questions