简体   繁体   中英

How to get Reference Fields in embedded block's using Gatsby and Contentful's Rich Text fields

I have a rich text editor field that accepts an embedded block where the content type contains a reference link to another content type.

Like this:

content (rich text field)
  - group (embedded block)
    - group-items (reference field)
      - item 1 (referenced content)
      - item 2 (referenced content)

How can I get the referenced content items using @contentful/rich-text-react-renderer ?

I currently have this:

import { MARKS, BLOCKS } from '@contentful/rich-text-types';
import { documentToReactComponents } from '@contentful/rich-text-react-renderer';

const options = {
  renderNode: {
    [BLOCKS.EMBEDDED_ENTRY]: (node) => {
      console.log(node);
      return true;
    }
  },
  renderText: text => text.replace('!', '?'),
};

Which gives me a bunch of id's but not of the field data for the entries which is what I really want.

content: []
data:
target: {sys: {…}}
__proto__: Object
nodeType: "embedded-entry-block"

content: []
data:
target:
sys: {id: "c13cBu2W6nOkQMx6bsvqCE5", type: "Link", linkType: "Entry"}
__proto__: Object
__proto__: Object
nodeType: "embedded-entry-block"
__proto__: Object

There where 2 problems I was running into here.

Firstly coccasionally Gatsby's cache will cause issues retriving new data from contentful and as such you may only get sys not fields . Which is what was happening to me.

Just delete .cache and rerun yarn run dev and it should be good.

Secondly to get multiple contentTypes with enter blocks this can be achieved by looking for the Entry blocks sys.id . This way you can create different components to handle various content types.

[BLOCKS.EMBEDDED_ENTRY]: (node) => {
      const fields = node.data.target.fields;

      switch (node.data.target.sys.contentType.sys.id) {
        case 'group-item':
          return <div>
            <GroupItem name={fields.name['en-US']} />
          </div>
        default:
           return <div>Fallback Element</div>
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM