Search code examples
reactjswordpresswordpress-gutenberggutenberg-blocks

Gutenberg blocks: RichText default value displaying HTML tags


When I include tags in the following Gutenberg block it outputs the HTML tags in both the editor and the frontend. This is only happening with default text-- when adding a link from within the editor it renders correctly:

attributes: {
  text: {
    type: 'array',
    source: 'children',
    selector: 'p',
    default: 'Here is the test <a href="https://example.com">link</a>',
  },
}

edit: ({ attributes: { text }, setText ) => {
  return <RichText
    placeholder="Text..."
    tagName="p"
    onChange={setText}
    value={text}
    allowedFormats={['core/bold', 'core/italic', 'core/link']}
  />
}

save: () => {
  return <RichText.Content tagName="p" value={text} />
}

Outputs (wrapped in <p> tag):

Here is the test <a href="https://example.com">link</a>

Have tried copying markup from the Gutenberg core/link exactly:

default: 'Here is the test <a href="https://example.com">link</a>'

Outputs (wrapped in <p> tag):

Here is the test <a href="https://example.com">link</a>

And have tried setting the default text with the tag as an object:

default: `Here is the test ${<a href="https://example.com">link</a>}`

Outputs (wrapped in <p> tag):

Here is the test [object Object]

How can I get this default text to output the tags themselves?


Solution

  • The RichText component placeholder text supports plain text only. However, you can add preformatted content like links and other supported formatting by defining example content within the block properties:

    ...
    attributes: {
        text: {
            type: 'array',
            source: 'html',
            selector: 'p'
        },
    },
    example: {
        attributes: {
            text: 'Here is the test <a href="https://example.com">link</a>'
        }
    },
    ...
    

    By defining the example attribute, placeholder= ... and default: ... are no longer needed and the 'example link' will be editable.