Disclaimer: This website requires Please enable JavaScript in your browser settings for the best experience.

HomeDev GuideRecipesAPI Reference
Dev GuideAPI ReferenceUser GuideGitHubNuGetDev CommunityOptimizely AcademySubmit a ticketLog In
Dev Guide

Common use cases and best practices

Learn how the RichText component renders Optimizely CMS content in React, including customization patterns, fallback behavior, and best practices for performance, accessibility, and type safety.

The RichText component renders and normalizes Optimizely CMS rich text content in React, including attribute and style processing, safe fallback behavior for unsupported elements, customization through custom renderers, and recommended best practices to ensure consistent, accessible, and type-safe output.

Common Use Cases

The RichText component supports a wide range of rendering scenarios by allowing you to override specific elements while relying on optimized defaults for all other content.

Blog Content

Use custom element renderers to apply editorial styling while preserving semantic HTML.

<RichText
  content={post.content?.json}
  elements={{
    'heading-one': ({ children }) => (
      <h1 className="article-title">{children}</h1>
    ),
    paragraph: ({ children }) => (
      <p className="article-paragraph">{children}</p>
    ),
  }}
/>

Documentation

Override code-related elements to integrate with custom formatting or syntax-highlighting components.

<RichText
  content={doc.body?.json}
  elements={{
    code: ({ children }) => <CodeBlock>{children}</CodeBlock>,
    pre: ({ children }) => <PreformattedText>{children}</PreformattedText>,
  }}
  decodeHtmlEntities={false} // Preserve code entities
/>

Use decodeHtmlEntities={false} when rendering code examples to preserve encoded characters.

Marketing Content

Enhance interaction tracking or analytics by wrapping link elements in custom components.

<RichText
  content={page.content?.json}
  elements={{
    link: ({ children, element }) => (
      <TrackableLink url={element.url} eventName="content-click">
        {children}
      </TrackableLink>
    ),
  }}
/>

Best Practices

Follow these recommendations when customizing RichText rendering:

  • Performance – Only override elements/leafs you need to customize - the default implementations are optimized
  • Accessibility – Maintain semantic HTML structure in custom components - screen readers depend on proper markup
  • Type Safety – Use TypeScript interfaces for better development experience and catch errors at compile time
  • Unknown Elements – The default <span> fallback handles unknown elements safely - no configuration needed