Allow alignment in custom Gutenberg blocks

Posts

If you’re developing a gutenberg block but can’t activate the alignment options, limit the ability to activate only a few alignments, or activate only one default alignment without giving the user a chance to change it, then here’s a brief explanation of how to do it.

How to allow all or some alignment options

Here in the WordPress handbook you can find a pretty useful configuration named supports.

Inside your registerBlockType() insert supports.

If you want all the alignment options available leave it like this:

registerBlockType(
  ...
  supports {
    align:true
  },
  ...
)

This way all alignment options will be available, otherwise you can choose which ones to insert:

registerBlockType(
  ...
  supports {
    align:true,
    align: ['left','right','wide']
  },
  ...
)

So only the left, right and wide alignment will be available.

Set an alignment without giving the option to change it

If, on the other hand, we want the user to insert our block into the page directly with a specific alignment, without having the ability to change it, then here’s how you do it.

Let’s first add a constant before registerBlockType() with the alignment we want, for example wide

const validAlignments = ['wide']

Add align to attributes, like this

registerBlockType(
  ...
  attributes{
    align {
      type:'string',
      default:'wide'
    },
    ...
  },
  ...
)

There is one function that is already used in the core of WordPress, which is this:

getEditWrapperProps( attributes ) {
  const align = { attributes };
  if ( -1 !== validAlignments.indexOf( align ) ) {
    return { 'data-align': align };
  }
}

Insert it into your getEditWrapperProps(), like this

registerBlockType(
  ...
  getEditWrapperProps( attributes ) {
    const align = { attributes };
    if ( -1 !== validAlignments.indexOf( align ) ) {
      return { 'data-align': align };
    }
  },
  attributes{
    align {
      type:'string',
      default:'wide'
    },
    ...
  },
  ...
)

Now every time the block is inserted in the page, it will be inserted with the wide alignment already activated and the user will not be able to modify it.