Add Text-align Control to Gutenberg Block Toolbar

Published
Categories

First add a new attribute to hold the state of the alignment:

{
	// ...other block settings
	"attributes": {
		// ...other block attributes
		"textAlign": {
			"type": "string"
		}
	}
}
Code language: JSON / JSON with Comments (json)

Then add WordPress’ alignment control to the block toolbar in the block’s edit function:

import {
	AlignmentToolbar,
	BlockControls,
} from "@wordpress/block-editor";

export default function myBlockEdit({ attributes, setAttributes }) {
	const { textAlign } = attributes;

	return (
		// apply class if textAlign is set
		<div className={textAlign ? `has-text-align-${textAlign}` : false}>
			// include alignment control
			<BlockControls>
				<AlignmentToolbar
					value={textAlign}
					onChange={(textAlign) => setAttributes({ textAlign })}
				/>
			</BlockControls>
			<p>My Block!</p>
		</div>
	);
}
Code language: JavaScript (javascript)

From there, the same attribute can be used in a save function or in a PHP render callback for dynamic blocks to apply the text align class on the front-end.