...

/

Customizing a Block

Customizing a Block

Learn how to add a toolbar with formatting options for the block.

The heading block displays a hard coded message on the editor as well as on the frontend screen. This lesson shows how to add custom content for the heading and style it. Before we delve into the lesson, let’s discuss some terminology.

Attributes

Attributes are essentially the properties or values that define the behavior and appearance of a block. Attributes help us manage our data. We can store data, update it, and show it to our users.

Attributes are defined as an object when registering block types. Every attribute has a name and a type. In addition, we can specify a default value. Attributes are essentially all the properties that we want to save for the block for example the content, font size, color etc for the heading block. We will add attributes to the block.json file.

Open the block.json in the heading folder. It contains a property called attributes, which is an object. We will nest other objects inside that represent each attribute. Let’s create an attribute called headingText. This is an object which contains the mandatory property type and optional properties named default, source, etc.

"attributes": {
"headingText": {
"type": "string",
"default": "Hello World!!"
}
}
headingText attribute

Attributes are available to both the edit and save functions. They help recreate the block from the saved markup to a JavaScript representation of a block.

Props

In the context of React, props are data that are passed to a block. WordPress passes props to the edit and save functions. The props object gives us access to the block’s attributes and method to update the attributes among other things.

Open the edit.js file and modify the edit function to accept props as an argument. To see what this object contains we can view its output in the console.

Press + to interact
Props
Props

The following properties in the props object are of interest to us:

  • The attributes object contains all the block’s attributes. We can see the headingText attribute we defined in block.json.

  • The className attribute shows a class which WordPress adds to our block. We can target this class to add custom styling to our block.

  • The clientId attribute shows the ID of the block. This Id is generated dynamically for every block. This property comes in handy when we want to target a particular block on the page.

  • The setAttributes is an important property which is used to change the value of attributes.

We can access the attribute headingText in the ...