Creating a single-width Gutenberg block

We have been creating websites using WordPress’ Gutenberg editor since the first stable version was released around the beginning of 2019. Most of the work we do relies on building custom blocks using React, so that our users can profit from the huge speed increases thanks to the new editor, whilst creating content for their sites using content blocks which are tailor-made for their own, specific requirements.

The Gutenberg editor (and a matching WordPress Theme) provide the opportunity for us to conceive and create content blocks in three sizes: regular, wide and full. Many of the custom blocks we’ve created have integrated layout adjustments for each of these sizes; adjusting the content automatically according to the chosen width. For example, a team list which features cards beneath each other in a narrower layout, which automatically changes to alternate grid layouts at wide and full sizes.

Sometimes, we’ve created blocks which need to be “forced” to a single width. The regular layout is simple to achieve: just pass an empty array to the supports property in the block configuration. But how to force a block to only be available in, for example, full-width alignment?

Most of the work is easy: just ensure that the containing HTML block always contains the alignfull CSS class name. However, in order to make sure that the block’s editorial interface is correct, you’ll also need to ensure that the containing DIV in the Gutenberg editor has the appropriate data-align attribute set. That’s relatively simple too: add the following JavaScript call to the block’s componentDidMount function.

document.querySelector('#block-' + this.props.clientId).setAttribute('data-align', 'full');

Update from Pascal Knecht: you can alternatively use the getEditWrapperProps function.

getEditWrapperProps( attributes ) {
	return {...attributes, 'data-align': 'full' };
},

Leave a Reply

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