Search

How to render React components from embedded entries in a Contentful rich text field

When you embed an entry in a Contentful rich text field, you need to configure your front end to render this properly from a Contentful response. By the end of this article, you'll have a clear understanding of how to do this using React.


The logic

The idea is to add an option to Contentful's rich-text-react-renderer to check for the referenced or embedded entry in the response data from Contentful.


As an example, we're going to assume someone wants to add two images next to each other in a Contentful rich text field. We'll call this component 🖼️ Side-by-side Images.


The code

This is the React component you can use to display images next to each other if the 🖼️ Side-by-side Images component is included in a Contentful response for a rich text field.



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

const SideBySideImages = (props) => {
  const embeddedContentfulEntry = (entry) => {
    if (entry.__typename === 'ContentfulComponentSideBySideImages') {
      // This will be different depending on how you name these fields in Contentful
      const { imageOneHref, imageTwoHref } = entry.data.target.fields;
      const componentStyle = {
        display: 'flex',
      }
      return (
        <div className="Side-By-Side-Images" style={componentStyle}>
          <img
            className="Side-By-Side-Images__File" 
            src={imageOneHref}
          />
          <img
            className="Side-By-Side-Images__File" 
            src={imageTwoHref}
          />
        </div>
      )
    }
  }

  const customRichTextOptions = {
    renderNode: {
      [BLOCKS.EMBEDDED_ENTRY]: embeddedContentfulEntry,
    }
  }

  if(props.data) {
    return (
      documentToReactComponents(props.data, customRichTextOptions);
    )
  }
}
  

This next question comes up a lot for people working with rich text fields.



Why am I mentioning this now? Almost every website made with Contentful will have UI that looks different than the native rich text rendering — this is why you're here, learning how to create the React components above in the first place.


Figuring out how to model components that can be referenced in rich-text fields will help you go even further, to a place where you know precisely how to create components that reflect other UI styles you have. This understanding will help you immensely as you grow your site with Contentful.


Grab our free guide below and learn to model mixed UI layouts in rich text fields like a Contentful pro.