Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
307 views
in Technique[技术] by (71.8m points)

web - Gatsby soruce contentful body

Hey I'm using gatsby srouce contentful get my blog post from contenful. I'm trying to get the body as rich text or json but the only option graphql will let me use is raw which gives me back a bunch of objects and the text which I don't want.

question from:https://stackoverflow.com/questions/65943128/gatsby-soruce-contentful-body

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

raw object is a new "feature" added in the latest versions of gatsby-source-contentful. According to the docs:

Note: Be aware that previous versions of the Gatsby Contentful source plugin used a json field. This got replaced with raw to give you more flexibility in rendering and to fix performance issues.

That "flexibility" that Contentful points, is the capability of customizing the output from the return statement of the component that will parse that raw response. Ideally, you should have something like:

import { BLOCKS, MARKS } from "@contentful/rich-text-types"
import { renderRichText } from "gatsby-source-contentful/rich-text"
?
const Bold = ({ children }) => <span className="bold">{children}</span>
const Text = ({ children }) => <p className="align-center">{children}</p>
?
const options = {
  renderMark: {
    [MARKS.BOLD]: text => <Bold>{text}</Bold>,
  },
  renderNode: {
    [BLOCKS.PARAGRAPH]: (node, children) => <Text>{children}</Text>,
    [BLOCKS.EMBEDDED_ASSET]: node => {
      return (
        <>
          <h2>Embedded Asset</h2>
          <pre>
            <code>{JSON.stringify(node, null, 2)}</code>
          </pre>
        </>
      )
    },
  },
}
?
renderRichText(node.bodyRichText, options)

The snippet above, allows you to customize the response for each MARKS and BLOCKS entry, adding the proper styles if desired and wrapping it in any structure that you may need. The component above will allow you to parse that raw response and return the correct component.

You can check for further details the Contentful docs provided in this answer and the gatsby-source-contentful plugin docs.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...