Last active
July 13, 2021 13:37
-
-
Save cezarsmpio/ddc119eb907bd216b900074cea099d89 to your computer and use it in GitHub Desktop.
Rendering Contentful rich text tables with the React renderer with Gatsby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module.exports = { | |
// ... all your other configs | |
plugins: [ | |
// ... all your other plugins | |
{ | |
resolve: `gatsby-source-contentful`, | |
options: { | |
spaceId: process.env.CONTENTFUL_SPACE_ID, | |
accessToken: process.env.CONTENTFUL_API_KEY, | |
environment: process.env.CONTENTFUL_SPACE_ENVIRONMENT, | |
}, | |
}, | |
], | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as React from "react" | |
import { graphql } from "gatsby" | |
import { BLOCKS } from "@contentful/rich-text-types" | |
import { documentToReactComponents } from "@contentful/rich-text-react-renderer" | |
import Layout from "../components/layout" | |
const options = { | |
renderNode: { | |
[BLOCKS.TABLE]: (node, children) => ( | |
<table> | |
<tbody>{children}</tbody> | |
</table> | |
), | |
[BLOCKS.TABLE_ROW]: (node, children) => <tr>{children}</tr>, | |
[BLOCKS.TABLE_CELL]: (node, children) => <td>{children}</td>, | |
}, | |
} | |
const IndexPage = props => ( | |
<Layout> | |
<h1>Articles</h1> | |
<div> | |
{props.data.articles.nodes.map((article, index) => ( | |
<div key={index}> | |
<h1> | |
{article.title} | |
</h1> | |
<div> | |
{documentToReactComponents(JSON.parse(article.body.raw), options)} | |
</div> | |
</div> | |
))} | |
</div> | |
</Layout> | |
) | |
export default IndexPage | |
export const query = graphql` | |
query MyQuery { | |
articles: allContentfulArticle { | |
nodes { | |
title | |
body { | |
raw | |
} | |
} | |
} | |
} | |
` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment