Render Code Block from Rich Text Field

I have a Rich Text Field in my Content Model for a blog post. I want to have some portion of this blog post to display a code block for various articles my editors will write.

Does anyone know how to render code blocks from the Rich Text Field?

1 Like

One way you can do this is by using a Content Type representing the code block. You will be able to insert the code block as an inline entry and paste the code in a long text field inside the CT. Then you can differentiate the Code Block from the rest of the Rich Text content and render it differently.

What stack are you using?

Both @contentful/rich-text-html-renderer and @contentful/rich-text-react-renderer make it really easy to slot in custom stuff for specific richtext blocks and marks.

import { MARKS } from '@contentful/rich-text-types';

import RichText from '@madebyconnor/rich-text-to-jsx';


<RichText
    richText={details} //details is the richtext field type coming from contentful
    overrides={{
       [MARKS.CODE]: (node) => {
           return <div className="px-6 py-3 my-4 bg-gray-500 text-blue-300 font-mono rounded-lg">{node.children}</div>
           }
    }}
/>

btw Iā€™m using tailwind in a NEXT JS project

I was using @contentful/rich-text-react-renderer and I could not get the code blocks to render side by side. They kept rendering on their own line and it was driving me nuts. Each code block was wrapped in a p tag. So I ended up mutating the object. Works great, feel and looks like my toe fungus.


const selectWithCodeWrapper = ( content: Document ): Document => {
  const nodes = [
    ...content.content 
  ] || [
  ]
  try {
    for( let i = nodes.length - 1; i > -1; i -- ) {
      if( 
        nodes[ i ] && 
      nodes[ i - 1 ] &&
      nodes[ i ].nodeType === BLOCKS.PARAGRAPH 
      && ( nodes[ i ].content[ 0 ] as any )?.marks?.[ 0 ]?.type === MARKS.CODE 
      && ( nodes[ i - 1 ].content[ 0 ] as any )?.marks?.[ 0 ]?.type === MARKS.CODE
      ) {
        ( nodes[ i - 1 ].content[ 0 ] as any ).value += `\r` + ( nodes[ i ]?.content[ 0 ] as any ).value
        delete nodes[ i ]
      }
    }
    return {
      ...content,
      content: nodes 
    }
  } catch ( e ) {console.error( e )} return content}