I have a custom Gutenberg block which is attempting to take an array of strings and save them as <li> elements. Everything works as expected and displays correctly to the end user, but I’m getting validation errors after reloading the editor.

Here is the validation error:

Expected:

<div class="wp-block-ggcn-blocks-query-string-content"><span class="data-drop" newtab=""></span><ul class="tabs"><li class="tab"><li class="tab">Tab1</li></li><li class="tab"><li class="tab">Tab2</li></li></ul><p class="custom-content"></p></div>

Actual:

<div class="wp-block-ggcn-blocks-query-string-content"><span class="data-drop" newtab=""></span><ul class="tabs"><li class="tab">Tab1</li><li class="tab">Tab2</li></ul><p class="custom-content"></p></div>

Here is my save function:

save({attributes, className}) {
  const { tabs, newTab, content } = attributes;

  return (
    <div className={className}>
      <span className="data-drop" newtab={newTab}></span>
      <ul className="tabs">
      {tabs.map(tab => {
            return <li className="tab">{tab}</li>;
        })}
      </ul>          
    </div>
  );
}

Here is how I’m parsing the attributes:

attributes: {
  tabs: { 
    type: 'array',
    source: 'children',
    selector: 'ul.tabs',
    default: []
  }
}

Obviously I’m parsing out the entire HTML list elements, when I only want the text. But when I change the selector to be ul.tabs > li, I get only the text for a single element, and lists of more than 1 item fail validation.

Can someone help me understand how to get an array of text values?

2 Answers
2

I found a workaround, sparked by @tmdesigned’s answer, which I’m going to post as an answer. It is not pretty and I don’t think it can be the “canonical” answer, but hopefully it helps us get there.

So first, I kept the attributes using a source: children:

tabs: { 
  type: 'array',
  source: 'children',
  selector: 'ul.tabs',
  default: []
}

This meant that on initial save, I was dealing with an array of strings, but on subsequent loads in the editor, I was dealing with an array of objects, since my source type of children was pulling in the <li> elements themselves in the list, instead of the text values of the elements.

My solution was to map over these elements and convert them back into an array of strings. This had to be done in both the edit function and the save function.

const tabValues = tabs.map(tab => {
  if (typeof(tab) === 'object')
    return tab.props.children[0];

  return tab;
});

Then later in the output, I was able to output like this:

{tabValues.map(tab => <li key={tab} className="tab">{tab}</li>)}

If anyone has a solution that relies exclusively on the data parse and doesn’t require this workaround, I will mark that as the answer.

Leave a Reply

Your email address will not be published. Required fields are marked *