How to Create and Extend Block Toolbar Controls on WordPress Gutenberg Block Editor

Block Toolbar Controls is one of the best ways to simplify blocks and create a better user experience in the Gutenberg block editor. These controls are easily visible on each selected block, thus, giving instant access from the user. You have to make a better judgment when creating a block because too many block controls will clutter the editorial experience. In this tutorial, I will guide you on how to create and extend your Gutenberg block to have custom block toolbar controls.

1. Loading the Dependencies

To work with Block Toolbar Controls, you need to load the necessary dependencies. The main dependency is the BlockControls component, which is part of the @wordpress/block-editor module. This component serves as the wrapper for any toolbar controls you want to add to your blocks. Additionally, you may need to load other modules and components based on your specific requirements.

const { __ } = wp.i18n;
const { BlockControls } = wp.blockEditor;
const { DropdownMenu, MenuGroup, MenuItem, ToolbarGroup } = wp.components;

2. Create the Custom Block Toolbar Control

In this particular example, I will show you how to create a custom toolbar control with multiple options using dropdown component. These options will add and remove classes to the block wrapper and so you can apply background color to it.

const { __ } = wp.i18n;
const { BlockControls } = wp.blockEditor;
const { DropdownMenu, MenuGroup, MenuItem, ToolbarGroup } = wp.components;
const Controls = (props) => {
const { attributes, setAttributes } = props;
const { theme } = attributes;
const themes = [
{
key: '',
label: __('Default', 'custom-domain'),
},
{
key: 'dark',
label: __('Dark', 'custom-domain'),
},
{
key: 'retro',
label: __('Retro', 'custom-domain'),
},
{
key: 'vintage',
label: __('Vintage', 'custom-domain'),
},
];
return (
<BlockControls group="other">
<ToolbarGroup>
<DropdownMenu
icon={<span>{__('Theme', 'custom-domain')}</span>}
label={__('Switch Theme', 'custom-domain')}
>
{({ onClose }) => (
<MenuGroup>
{themes.map((themeData) => {
return (
<MenuItem
icon={theme === themeData.key ? 'yes' : ''}
onClick={() => {
setAttributes({ theme: themeData.key });
onClose();
}}
>
{themeData.label}
</MenuItem>
);
})}
</MenuGroup>
)}
</DropdownMenu>
</ToolbarGroup>
</BlockControls>
);
};
export default Controls;
view raw controls.js hosted with ❤ by GitHub

3. Add Block Controls Component to the Gutenberg Block

Now that the custom Javascript component for the Block Toolbar Control has been created add it to your block’s edit component. In the example below, I’ve also added the block registration to make it more informative.

import Controls from './controls'; // Make sure that the import path is correct
const { registerBlockType } = wp.blocks;
const { useBlockProps } = wp.blockEditor;
registerBlockType('gutenberg-examples/example-block-controls', {
apiVersion: 3,
title: 'Example: Controls',
icon: 'align-full-width',
attributes: {
theme: {
type: 'string',
default: '',
},
},
category: 'design',
edit: (props) => {
const { attributes } = props;
const { theme } = attributes;
const blockProps = useBlockProps({
className: `theme-${theme}`,
});
return (
<>
<Controls {…props} />
<div {…blockProps}>Your Block Content Here</div>
</>
);
},
save: (props) => {
const blockProps = useBlockProps.save();
return <div {…blockProps}>Your Block Content Here</div>;
},
});

4. Extending an Existing Block with Custom Block Toolbar Control

If you want to extend an existing block with a custom block toolbar control, follow the steps below. This approach involves registering the necessary block attributes and including the custom component created earlier.

/**
* Add Custom Block Control to Existing Block
*/
import Controls from './controls';
const { createHigherOrderComponent } = wp.compose;
const { Fragment } = wp.element;
const allowedBlocks = ['core/group']; // Enable control to existing Group block
/**
* Add custom attribute
*/
function addAttributes(settings) {
// Check if attributes exists and compare the block name
if (typeof settings.attributes !== 'undefined' && allowedBlocks.includes(settings.name)) {
settings.attributes = Object.assign(settings.attributes, {
theme: {
type: 'string',
default: '',
},
});
}
return settings;
}
wp.hooks.addFilter('blocks.registerBlockType', 'example/add-atttibutes', addAttributes);
/**
* Add Custom Block Controls
*/
const addBlockControls = createHigherOrderComponent((BlockEdit) => {
return (props) => {
const { name, isSelected } = props;
if (!allowedBlocks.includes(name)) {
return <BlockEdit {…props} />;
}
return (
<Fragment>
{isSelected && <Controls {…props} />}
<BlockEdit {…props} />
</Fragment>
);
};
}, 'addBlockControls');
wp.hooks.addFilter('editor.BlockEdit', 'example/add-block-controls', addBlockControls);

By following these steps, you can create and extend block toolbar controls in the WordPress Gutenberg block editor. Experiment with different controls and functionalities to enhance the editing experience and provide users with a more intuitive interface. Remember to customize the code examples to match your specific requirements and design preferences.

Feel free to explore the official WordPress documentation for more detailed information and additional options related to block toolbar controls in Gutenberg. Happy coding!

Leave a Reply

I won’t send you spam. Unsubscribe at any time.

Discover more from Jeffrey Carandang

Subscribe now to keep reading and get access to the full archive.

Continue reading