Strapi Blocks React Renderer

repository·main·Indexed 42 days ago

https://github.com/strapi/blocks-react-renderer

A utility for rendering JSON-based 'Blocks' rich text format from Strapi into React components. Version 1.0.2 provides the BlocksRenderer component and BlocksContent type, allowing developers to render Strapi API content and customize rendering behavior via blocks and modifiers props for elements like paragraphs, headings, and inline styles.

Tokens
2.1K
Snippets
8
Records
8
Agent score
52%

What's inside Strapi Blocks React Renderer

  1. Customize Blocks and Modifiers in BlocksRenderer

    main

    You can override the default rendering behavior by providing custom React components via the blocks and modifiers props. These custom components are merged with the defaults, allowing you to override only specific elements.

    Blocks

    Blocks are full-width, root-level elements. Supported types include:

    • paragraph
    • heading (receives level and plainText)
    • list (receives format)
    • quote
    • code (receives plainText)
    • image (receives image)
    • link (receives url)

    Modifiers

    Modifiers are inline elements used to style text fragments within a block. Supported types include:

    • bold
    • italic
    • underline
    • strikethrough
    • code

    Important: When providing custom components, you must ensure that you render the children prop so that nested blocks and modifiers are correctly rendered.

    import { BlocksRenderer } from '@strapi/blocks-react-renderer';
    
    // Content should come from your Strapi API
    const content = [
      {
        type: 'paragraph',
        children: [{ type: 'text', text: 'A simple paragraph' }],
      },
    ];
    
    const App = () => {
      return (
        <BlocksRenderer
          content={content}
          blocks={{
            // You can use the default components to set class names...
            paragraph: ({ children }) => <p className="text-neutral900 max-w-prose">{children}</p>,
            // ...or point to a design system
            heading: ({ children, level }) => {
              switch (level) {
                case 1: return <Typography variant="h1">{children}</Typography>
                case 2: return <Typography variant="h2">{children}</Typography>
                case 3: return <Typography variant="h3">{children}</Typography>
                case 4: return <Typography variant="h4">{children}</Typography>
                case 5: return <Typography variant="h5">{children}</Typography>
                case 6: return <Typography variant="h6">{children}</Typography>
                default: return <Typography variant="h1">{children}</Typography>
              }
            },
            // For links, you may want to use the component from your router or framework
            link: ({ children, url }) => <Link to={url}>{children}</Link>,
          }}
          modifiers={{
            bold: ({ children }) => <strong>{children}</strong>,
            italic: ({ children }) => <span className="italic">{children}</span>,
          }}
        />
      );
    };
  2. Install @strapi/blocks-react-renderer

    main

    Install the Blocks renderer along with its required peer dependencies react and react-dom using your preferred package manager.

    yarn add @strapi/blocks-react-renderer react react-dom
    npm install @strapi/blocks-react-renderer react react-dom
  3. Define custom text modifiers for the Blocks Renderer

    main

    When customizing the @strapi/blocks-react-renderer, you can provide custom React components for text modifiers. The renderer identifies modifiers based on the keys present in a TextInlineNode.

    Available modifier keys include:

    • bold
    • italic
    • underline
    • strikethrough
    • code

    If you provide a component for a modifier key in your components prop, the renderer will wrap the text node with that component. If a modifier is present in the data but no component is provided in the context, a warning is logged to the console: [@strapi/block-react-renderer] No component found for modifier "<modifierName>".

    // Example of how modifiers are structured in the data
    const textNode = {
      type: 'text',
      text: 'Hello World',
      bold: true,
      italic: true
    };
    
    // When rendering, the renderer looks for components matching the keys:
    // components={{ 
    //   bold: ({ children }) => <strong>{children}</strong>, 
    //   italic: ({ children }) => <em>{children}</em> 
    // }}
  4. Basic usage of BlocksRenderer

    main

    To render content from Strapi's Blocks rich text editor, use the BlocksRenderer component. Pass the array of blocks retrieved from your Strapi API to the content prop. The content prop expects a type of BlocksContent.

    import { BlocksRenderer, type BlocksContent } from '@strapi/blocks-react-renderer';
    
    // Content should come from your Strapi API
    const content: BlocksContent = [
      {
        type: 'paragraph',
        children: [{ type: 'text', text: 'A simple paragraph' }],
      },
    ];
    
    const App = () => {
      return <BlocksRenderer content={content} />;
    };
  5. Use the BlocksContent type

    main

    The BlocksContent type represents the structure of the Strapi Blocks JSON data. It is defined as an array of RootNode objects. Use this type when defining props or state that hold the raw blocks data received from the Strapi API.

    import type { BlocksContent } from '@strapi/blocks-react-renderer';
    
    const myContent: BlocksContent = [
      // ... blocks data
    ];
  6. Use the BlocksRenderer component

    main

    The BlocksRenderer component is the primary entry point for rendering Strapi Blocks JSON content in a React application. It takes the blocks data and renders it into a structured UI.

    import { BlocksRenderer } from '@strapi/blocks-react-renderer';
    
    // Assuming 'content' is the JSON data received from Strapi
    <BlocksRenderer content={content} />
  7. TextInlineNode type definition

    main

    The TextInlineNode interface defines the structure of an inline text node within the Strapi Blocks format. It includes the raw text and optional boolean modifiers that determine how the text should be styled.

    interface TextInlineNode {
      type: 'text';
      text: string;
      bold?: boolean;
      italic?: boolean;
      underline?: boolean;
      strikethrough?: boolean;
      code?: boolean;
    }
  8. Modifier type definition

    main

    The Modifier type represents the set of available styling keys for text nodes, excluding the mandatory type and text properties.

    type Modifier = Exclude<keyof TextInlineNode, 'type' | 'text'>;
    // Resulting type: 'bold' | 'italic' | 'underline' | 'strikethrough' | 'code'