3

I'm tring to make dynamic custom block using "RichText" and wondering how to set it's attributes. By checking examples on the internet, some people set its attributes to "Array & Children" but I also found the examples with "HTML & Class Name".

I tried both patterns(Pattern A and B below) but their results on frontend are exactly the same. I'd like to know the difference between them and which is the better way.

Pattern A

attributes: {
    message: {
        type: 'array',
        source: 'children',
        selector: '.message',
    }
},

Pattern B

attributes: {
    message: {
        type: 'string',
        source: 'html',
        selector: '.message',
    }
},

edit & save functions

edit: props => {
    const {attributes:{message}, className, setAttributes} = props;
    const onChangeMessage = message => {
        setAttributes({message});
    }
    return(
        <div className={ className }>
            <RichText
                tagName = "div"
                multiline = "p"
                onChange = {onChangeMessage}
                value = {message}
            />
        </div>
    );
},
save: props => {
    const {attributes:{message}} = props;
    return (
        <div>
            <div class="message">
                <RichText.Content
                    value = {message}
                />
            </div>
        </div>
    );

},

abms
  • 545
  • 1
  • 3
  • 13

1 Answers1

3

Attribute sources are used to define how the block attribute values are extracted from saved post content. They provide a mechanism to map from the saved markup to a JavaScript representation of a block.

Gutenberg uses attributes and attribute sources to parse that HTML out and extract data from it. In order to do this, Gutenberg makes use of the hpq library, which is a helper that does exactly this kind of parsing. Each source attribute describes a different function from hpq that’s used to parse an HTML block.

There attributes are passed on to the save and edit functio.

Attributes source depends on your usecase:

html: An html source will return you the innerHTML from the markup.

children: Using a children source attribute returns you the DOM nodes as an array of children

A children attribute is more flexible to extract complex HTML from your block and edit them and most of the time this what you must be using.

You can look at the other list of attributes provided by RichText here and also refer this really indepth blog on Attributes

Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400