Search code examples
wordpresswordpress-gutenberg

WordPress Gutenberg RichText, how can I set a default value with source: 'children' when using `multiline="p"`?


While registering a new block, I cannot set a default value if using a RichText with a multiline tag

  attributes: {
    header: {
      type: 'string',
      source: 'text',
      selector: 'h2',
      default: 'default',
    },
    text: {
      type: 'array',
      source: 'children',
      selector: 'div',
      default: 'Lorem Ipsum Dolor Sit Amet',

//    also tested, same result
//    default: ['Lorem Ipsum Dolor Sit Amet', 'test', 'test2'],
//    default: () => <p>Lorem Ipsum Dolor Sit Amet</p>,
//    default: [() => <p>Lorem Ipsum Dolor Sit Amet</p>],

    },
  },
  edit: ({ attributes: { header, text }, setAttributes }) => {
    const blockProps = useBlockProps()

    return (
      <div {...blockProps}>
        <RichText tagName="h2" placeholder={'Header'} onChange={header => setAttributes({ header })} value={header} />
        <RichText
          tagName="div"
          multiline="p"
          placeholder={'Write here the description'}
          onChange={text => setAttributes({ text })}
          value={text}
        />
      </div>
    )
  },

If I remove the multiline="p" line, I see the default text, but with it I don't see anything

Where's the error?


Solution

  • An alternative simplified way using the attributes to set a default for RichText with multiline="p" is:

        attributes: {
        ...
        text: {
            type: 'string', // changed from array
            source: 'children',
            selector: 'div',
            default: [<p>Lorem Ipsum Dolor Sit Amet</p>, <p>test</p>, <p>test2</p>]
        }