Introduction
In the previous article, we created our first custom Gutenberg block. Today, we’re going to dive deeper into one of the most powerful aspects of Gutenberg block development: block attributes.
Block attributes allow you to store, manipulate, and display dynamic data in your blocks. Whether it’s simple text, media files, colors, or more complex settings, attributes make blocks flexible and customizable for users. In this guide, we’ll explore how attributes work, the different types of attributes you can use, and how to implement them in your custom blocks.
What Are Gutenberg Block Attributes?
Attributes in Gutenberg blocks are data containers that store the state of your block. For example, if your block allows users to enter a title, change a color, or upload an image, attributes store these values.
When a block is inserted into the Block Editor, users can modify the block’s content and settings via the attributes. These attributes are then saved in the block’s markup or as block metadata, ensuring that the settings persist even after the post is saved.
Common Use Cases for Block Attributes
- Text input (e.g., headlines, paragraphs, button labels)
- Media selection (e.g., images, videos, audio files)
- Color settings (e.g., background color, text color)
- Boolean values (e.g., toggling features on/off)
- URL links (e.g., hyperlinks in buttons or images)
Step 1: Defining Block Attributes in block.json
The easiest way to define block attributes is in the block.json
file. Let’s modify the block we created in Day 3 by adding more attributes.
Open the block.json
file in your block folder (blocks/my-first-block/block.json
), and update the attributes section to include a few more attributes:
{
"apiVersion": 2,
"name": "your-theme/my-first-block",
"title": "My First Block",
"category": "common",
"icon": "smiley",
"description": "A custom Gutenberg block created for learning purposes.",
"supports": {
"html": false
},
"attributes": {
"content": {
"type": "string",
"source": "html",
"selector": "p"
},
"backgroundColor": {
"type": "string",
"default": "#f5f5f5"
},
"isBold": {
"type": "boolean",
"default": false
}
},
"textdomain": "your-theme",
"editorScript": "file:./index.js",
"style": "file:./style.css"
}
Explanation:
content
: A simple text attribute that stores the block’s text.backgroundColor
: This stores the background color for the block, with a default value of#f5f5f5
.isBold
: A boolean attribute that will toggle bold styling for the block’s content. By default, it’s set tofalse
.
Step 2: Using Attributes in the Block’s Edit Function
Now that we’ve defined the attributes, let’s modify the block’s edit
function to allow users to interact with these attributes in the Block Editor.
Open index.js
and update the code to handle the new attributes:
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}
/>
<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: Adds a settings panel to the Block Editor sidebar where users can modify block settings.
- ColorPalette: Provides a color picker to change the block’s background color.
- ToggleControl: Allows the user to toggle whether the text should be bold or not.
- Attributes in
save
: The block’ssave
function uses the attribute values (e.g.,backgroundColor
andisBold
) to apply styles when the block is rendered.
Step 3: Save and Test Your Block
With the new attributes in place, follow these steps to test your block:
- Rebuild Your Block: Run the following command in your terminal to rebuild the block:
npm run start
- Add the Block to a Post: Go to your WordPress admin dashboard, create a new post, and add “My First Block”.
- Test the Attributes:
- Use the ColorPalette in the block settings sidebar to change the background color.
- Toggle the Bold Text option to see how the text style changes.
- Enter and edit the block content using the RichText component.
Types of Attributes in Gutenberg
- String: Used for text content, such as headings, paragraphs, or button labels.
- Boolean: A true/false value, perfect for toggling options (e.g., bold text, show/hide).
- Number: Numeric values, useful for attributes like padding, margin, or font size.
- Array: Stores lists of items, such as image galleries or lists of links.
- Object: Used for more complex data, such as metadata or settings with multiple properties.
Conclusion: Mastering Block Attributes
Block attributes are an essential part of customizing your Gutenberg blocks. They allow your blocks to store dynamic data, provide rich customization options for users, and enable powerful flexibility in how content is displayed.
With attributes, you can make your blocks far more interactive and functional. In Day 5, we’ll explore advanced block styling techniques to further enhance the visual presentation of your blocks.
Stay tuned!
Leave a Reply