Introduction
Welcome to Day 6 of your Gutenberg development journey! So far, you’ve learned how to create custom blocks and style them using both CSS and inline styles. Now, it’s time to take your blocks to the next level by adding Inspector Controls, which allow users to modify block settings directly from the editor’s sidebar.
In this guide, we’ll show you how to add custom controls, such as toggles, dropdowns, and color pickers, to your Gutenberg blocks using InspectorControls. By the end of this tutorial, you’ll be able to give users full control over how their blocks behave and look, all from the familiar WordPress Block Editor.
What are Inspector Controls in Gutenberg?
Inspector Controls in Gutenberg refer to the sidebar settings that allow users to customize a block. These settings provide a user-friendly way to modify block attributes without touching the block’s content directly. From adjusting colors and selecting fonts to toggling display options, Inspector Controls make blocks more versatile and customizable.
Common Inspector Controls include:
- Color Palette: For selecting background and text colors.
- Toggle Control: For switching features on/off (boolean attributes).
- Text Control: For entering custom values like padding or margin.
- Select Control: For creating dropdowns with pre-defined options.
Step 1: Adding Basic Inspector Controls
To start, let’s add InspectorControls to a block we created earlier. This will allow us to add custom settings for background color and text formatting.
Open the index.js
file of your block (e.g., blocks/my-first-block/index.js
) and modify the block’s edit
function as follows:
import { registerBlockType } from '@wordpress/blocks';
import { RichText, InspectorControls, ColorPalette } from '@wordpress/block-editor';
import { PanelBody, ToggleControl } from '@wordpress/components';
import { __ } from '@wordpress/i18n';
registerBlockType('your-theme/my-first-block', {
title: __('My First Block', 'your-theme'),
description: __('A simple Gutenberg block for learning purposes.', 'your-theme'),
category: 'common',
icon: 'smiley',
attributes: {
content: {
type: 'string',
source: 'html',
selector: 'p',
},
backgroundColor: {
type: 'string',
default: '#f5f5f5',
},
isBold: {
type: 'boolean',
default: false,
},
},
edit: (props) => {
const { attributes: { content, backgroundColor, isBold }, setAttributes } = props;
const onChangeContent = (newContent) => {
setAttributes({ content: newContent });
};
const onChangeBackgroundColor = (newColor) => {
setAttributes({ backgroundColor: newColor });
};
const onToggleBold = () => {
setAttributes({ isBold: !isBold });
};
return (
<>
<InspectorControls>
<PanelBody title={__('Block Settings', 'your-theme')}>
<ColorPalette
value={backgroundColor}
onChange={onChangeBackgroundColor}
label={__('Background Color', 'your-theme')}
/>
<ToggleControl
label={__('Bold Text', 'your-theme')}
checked={isBold}
onChange={onToggleBold}
/>
</PanelBody>
</InspectorControls>
<RichText
tagName="p"
value={content}
onChange={onChangeContent}
placeholder={__('Enter your text here...', 'your-theme')}
style={{
backgroundColor,
fontWeight: isBold ? 'bold' : 'normal',
}}
/>
</>
);
},
save: (props) => {
const { attributes: { content, backgroundColor, isBold } } = props;
return (
<RichText.Content
tagName="p"
value={content}
style={{
backgroundColor,
fontWeight: isBold ? 'bold' : 'normal',
}}
/>
);
},
});
Explanation:
- InspectorControls: The
InspectorControls
component adds a settings panel in the Block Editor sidebar where users can adjust block attributes. - PanelBody: We use this component to group related controls. Here, we’ve added a ColorPalette for changing the background color and a ToggleControl for toggling bold text.
- ColorPalette: A color picker component that allows users to select a color for the block’s background.
- ToggleControl: A simple toggle switch that users can use to apply or remove the bold text style.
Step 2: Adding Advanced Controls (SelectControl and TextControl)
Next, let’s add more advanced controls such as a dropdown to choose text alignment and a text input for setting custom padding. These controls will allow even more customization for your block.
Add the following controls to the InspectorControls
component inside your edit
function:
import { SelectControl, TextControl } from '@wordpress/components';
const onChangeAlignment = (newAlignment) => {
setAttributes({ alignment: newAlignment });
};
const onChangePadding = (newPadding) => {
setAttributes({ padding: newPadding });
};
return (
<>
<InspectorControls>
<PanelBody title={__('Block Settings', 'your-theme')}>
<ColorPalette
value={backgroundColor}
onChange={onChangeBackgroundColor}
label={__('Background Color', 'your-theme')}
/>
<ToggleControl
label={__('Bold Text', 'your-theme')}
checked={isBold}
onChange={onToggleBold}
/>
<SelectControl
label={__('Text Alignment', 'your-theme')}
value={alignment}
options={[
{ label: __('Left', 'your-theme'), value: 'left' },
{ label: __('Center', 'your-theme'), value: 'center' },
{ label: __('Right', 'your-theme'), value: 'right' },
]}
onChange={onChangeAlignment}
/>
<TextControl
label={__('Padding (px)', 'your-theme')}
value={padding}
onChange={onChangePadding}
type="number"
/>
</PanelBody>
</InspectorControls>
<RichText
tagName="p"
value={content}
onChange={onChangeContent}
placeholder={__('Enter your text here...', 'your-theme')}
style={{
backgroundColor,
fontWeight: isBold ? 'bold' : 'normal',
textAlign: alignment,
padding: `${padding}px`,
}}
/>
</>
);
Explanation:
- SelectControl: A dropdown that lets users choose the text alignment (left, center, or right).
- TextControl: A simple input field where users can enter a custom value (like padding in pixels). This allows for more precise control over block layout.
Step 3: Saving Block Settings
To ensure that your settings are applied on both the editor and front end, you need to modify the save
function to include the new attributes (like alignment
and padding
).
Update the save
function in your index.js
file as follows:
save: (props) => {
const { attributes: { content, backgroundColor, isBold, alignment, padding } } = props;
return (
<RichText.Content
tagName="p"
value={content}
style={{
backgroundColor,
fontWeight: isBold ? 'bold' : 'normal',
textAlign: alignment,
padding: `${padding}px`,
}}
/>
);
},
Now, when users save the block, the settings they applied (such as background color, text alignment, and padding) will be rendered on the front end.
Step 4: Testing the Block
- Rebuild Your Block: Run the following command in your terminal to rebuild the block:
npm run start
- Test the Block in the Editor: Go to the WordPress dashboard and create a new post or page. Add your custom block, adjust the settings (color, text alignment, bold text, and padding), and see how they affect the block in real-time.
- Check the Front End: After publishing the post, view it on the front end to make sure the block’s settings are applied correctly, including custom text alignment and padding.
Inspector Controls: Common Use Cases
Adding custom block settings via Inspector Controls unlocks a lot of potential for your blocks. Here are some common use cases:
- Color Pickers: Allow users to choose custom colors for text, backgrounds, borders, or any other visual elements.
- Toggle Switches: Enable or disable features such as bold text, display options, or toggling visibility of block content.
- Text Inputs: Allow users to input custom values for spacing, font size, padding, or margin.
- Select Dropdowns: Let users choose between predefined options, such as alignment, font styles, or layouts.
- Media Uploaders: Enable users to upload images, videos, or audio files directly to the block.
By leveraging these controls, you empower users to customize the block’s behavior and appearance without needing to write any code.
Best Practices for Using Inspector Controls
When adding Inspector Controls to your Gutenberg blocks, keep the following best practices in mind:
- Keep It Simple: Don’t overload your block with too many options. Focus on providing settings that are essential for customizing the block’s appearance or behavior.
- Group Related Controls: Use
PanelBody
to group related controls together. This keeps the sidebar organized and makes it easier for users to find what they need. - Make Use of Defaults: Always provide sensible default values for attributes. This ensures that the block looks good out of the box, even if users don’t adjust the settings.
- Be Consistent: Follow the WordPress design guidelines when creating custom controls to ensure a consistent user experience.
- Use Descriptive Labels: Label your controls clearly so users can easily understand what each setting does.
Conclusion: Enhancing Block Flexibility with Inspector Controls
Inspector Controls are a powerful feature that adds flexibility and customization options to your Gutenberg blocks. By giving users access to the block’s settings directly from the editor sidebar, you allow them to tailor the block’s appearance and functionality to suit their needs without touching any code.
In this guide, you’ve learned how to:
- Add basic controls like color pickers and toggle switches.
- Incorporate advanced controls like dropdowns and text inputs for more granular control.
- Use and store block attributes with both the editor and front-end display.
In Day 7, we’ll continue building on these skills by diving into block templates and patterns, which allow you to create reusable block layouts and guide users on how to structure their content efficiently.
External Links:
Provide a link to the WordPress Gutenberg Inspector Controls Documentation for additional resources on controls.
Leave a Reply