Gatsby: Components for Contentful

Created on 26 Apr 2018  路  5Comments  路  Source: gatsbyjs/gatsby

Description

I want the ability to add Components to my Contentful pages/posts, has anyone managed to make this work since Contentful does just pass over Markdown for the body.

Been researching a fair bit.. tried using rehype-react throws out this error, assuming this is because i'm passing HTML and it's expecting HAST, which I'm unsure of how to convert to (that might fix the problem?):

Error: Expected root or element, not `<h1>hi from portfolio</h1>`

This is the code I'm using to reference it (in no particular order)

<div dangerouslySetInnerHTML={{ __html: renderAst(page.body.childMarkdownRemark.html), }} />

const renderAst = new rehypeReact({
  createElement: React.createElement,
  components: { 'react-collapsible': Collapsible, 'react-link': Link },
}).Compiler;

query PageBySlug($slug: String!) {
  contentfulPage(slug: {eq: $slug}) {
    title
    slug
    body {
      childMarkdownRemark {
        html
      }
    }
  }
}

Hope this makes sense and sorry if this isnt the correct place, trying to get ontop of how Github works with issues etc.

question or discussion

All 5 comments

I have no experience with this, but if it鈥檚 expecting AST, I believe you should be querying htmlAst instead of html.

query PageBySlug($slug: String!) {
  contentfulPage(slug: {eq: $slug}) {
    title
    slug
    body {
      childMarkdownRemark {
        htmlAst <-- this line changed
      }
    }
  }
}

Check out the docs @ if you haven't already https://using-remark.gatsbyjs.org/custom-components

Oh and yeah, like @ryanditjia said, query htmlAst.

I've tried with different remark plugins and so far I can't say I've found a good workflow for components+Markdown. There is another approach to have in mind. @kieranbs96 in case it works for you. Model your components in contentful and use composite content types.
https://www.contentful.com/blog/2018/04/25/get-up-to-speed-on-composable-entries/
https://www.contentful.com/blog/2015/09/10/creating-a-digital-lookbook/

@ryanditjia @KyleAMathews Can't believe it was that simple and thank you for a link to the Custom Components Docs - haven't seen those yet!

@proko Thanks for the info I will have a look at those articles.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

mikestopcontinues picture mikestopcontinues  路  3Comments

andykais picture andykais  路  3Comments

3CordGuy picture 3CordGuy  路  3Comments

rossPatton picture rossPatton  路  3Comments

jimfilippou picture jimfilippou  路  3Comments