How to Create Custom Gutenberg Blocks with React and WordPress?

Sunil Nagar
9 min readSep 8, 2022

--

Way: 1

How to Create Custom Gutenberg Blocks with React and WordPress?
\

What are Gutenberg blocks?

Gutenberg (named after Johannes Gutenberg who invented the first printing press) allows users to select pre-styled sections, or “blocks”, for each page and fill in the content. This makes for a much more fluid user experience when creating pages or blog posts. WordPress provides some default blocks which will probably work for a lot of casual users, but what if you need a special block for a particular page or you want a block with some different styles?

Rest assured, it is totally possible to create custom blocks. I will admit: at this time some of the documentation isn’t great for creating blocks but hopefully this post will help anyone getting started with Gutenberg to have a better understanding of the block development process.

Blocks in the theme or module?

Pretty much all of the tutorials I have seen about block creation address doing so in a plugin. In addition, many of them are creating a plugin for a single block. By following these tutorials, you’d need 30 separate plugins if you needed 30 custom blocks! I have created multiple blocks in a plugin and can definitely see the value in doing so if you have a lot of existing sites to add those blocks to. Doing so would allow you to update the module, push it to a remote git repository, then pull your changes into whatever sites needed the update.

When I was searching the other day, I couldn’t find any tutorials that explained how to set up custom blocks as a part of a theme. I believe there are some benefits to having the blocks in a theme rather than a plugin though, including (but not limited to) less dependencies to manage, keeping proprietary code for blocks specific to a website private, and not having to worry about a user accidentally disabling the plugin and breaking things.

Custom Gutenberg block theme setup

When I’m building a new WordPress site, I tend to use the Underscores theme which is made by Automattic. It’s a starter theme with very minimal styling. Although it can be downloaded with Sass structures in place, there is not a bundling tool included. I will be using Gulp to allow me to write jsx in my custom blocks. Before you can start developing the custom blocks, you need to add some code to the theme to handle it.

Blocks directory for custom blocks

To help keep things organized, I like to place all of my custom blocks into a directory in the root of my theme called blocks. This directory can be called whatever you like, but I'd recommed naming it something that is easily recognizable as custom blocks. In my case, the following command will create the directory:

# Terminal
$ mkdir blocks

Now that my blocks directory has been created, I need to create a php file inside which will enqueue my blocks and register my custom block types. I usually give mine the appropriate name of blocks.php though, again, you can call this whatever you like. The following command will create the file in my blocks directory and open it in the default code editor:

# Terminal
$ touch blocks/blocks.php && open $_

Create a function to register custom gutenberg blocks

The first thing you need to do in your blocks.php file (after the opening php tags) is create a function which will take care of adding the block scripts as well as registering the custom block type. I’ll take this step-by-step so it’s easy to follow. The empty function should look like this:

<!-- blocks/blocks.php -->
<?php
/**
* Enqueue scripts for custom blocks
*/
function custom_block_scripts() {
// Do something...
}
add_action('enqueue_block_assets', 'custom_block_scripts');

After creating the function, you’ll use a hook to call the function. Since adding Gutenberg to WordPress core, a new hook has been added called enqueue_block_assets which exists exactly for this purpose.

Enqueue the scripts and styles for the custom blocks

The next thing you need to do is include the scripts for the custom blocks you’re creating. This can be done using wp_enqueue_script() just like you'd do in a custom theme. This should go inside the custom_block_scripts() function like so:

<!-- blocks/blocks.php -->
<?php
/**
* Enqueue scripts for custom blocks
*/
function custom_block_scripts() {
// Add custom Gutenberg block scripts
wp_enqueue_script(
'custom-block-scripts',
get_template_directory_uri() . '/dist/js/blocks.js',
array(
'wp-blocks',
'wp-components',
'wp-element',
'wp-i18n',
'wp-editor'
),
'1.0.0',
true);
}
add_action('enqueue_block_assets', 'custom_block_scripts');

In the code above, you may notice that I have listed an array of dependencies. This is required for any WordPress components you want to use in your blocks. The ones I have listed here are the ones I find myself using most often. A full list of packages that are available can be found here. At a minimum, you need wp-blocks to register a block. The rest of the wp_enqueue_script() function should look pretty familiar if you've done theme development before. In case you haven't, here's a quick breakdown of the arguments:

<!-- wp_enqueue_script -->
<?php
wp_enqueue_script( $nickname, $location, $dependencies, $version, $in_footer );

Register the actual custom block types

Now that you have the scripts added, you need to use register_block_type() to tell WordPress what to do with the code. It should be noted that the $args array will use the nickname you chose in the previous step to identify the script or styles you want to use. Again, WordPress added a custom function to do this called register_block_type() with the following arguments:

<!-- register_block_type -->
<?php
register_block_type( $namespace, $args );

Based on the way you have set up the blocks so far, this is how your register_block_type() function will look:

<!-- register_block_type -->
<?php
register_block_type(
'iamtimsmith/blocks',
array(
'editor_script' => 'custom-block-scripts', // The script you enqueued earlier
)
);

The code above should go in the same custom_block_scripts() function where you are enqueuing your scripts. After you have set this up, your custom function should look like this:

<!-- blocks/blocks.php -->
<?php
/**
* Enqueue scripts for custom blocks
*/
function custom_block_scripts() {
// Add custom Gutenberg block scripts
wp_enqueue_script(
'custom-block-scripts',
get_template_directory_uri() . '/dist/js/blocks.js',
array(
'wp-blocks',
'wp-components',
'wp-element',
'wp-i18n',
'wp-editor'
),
'1.0.0',
true);
// Register custom block types
register_block_type(
'iamtimsmith/blocks',
array(
'editor_script' => 'custom-block-scripts',
)
);
}
add_action('enqueue_block_assets', 'custom_block_scripts');

Telling functions.php about the custom blocks

The final step for registering blocks in your theme is to add a call to the functions.php file. This will simply tell your theme that the file exists in the blocks directory and the content should be pulled in. While this step is relatively easy, it is also required for this to work. If you are running into issues with your custom blocks not showing up at all, I'd double check and make sure you added the call to your functions.php file. Adding the code below will tell your theme about the registered custom blocks:

// functions.php/**
* Add custom blocks for gutenberg
*/
require get_template_directory() . '/blocks/blocks.php';

Although it doesn’t matter where in your functions.php file you place the code, I tend to put it at the bottom. Especially if you're using the underscores theme, it helps to keep your code separated from the default theme code.

Way:2

You will do it with the help of a special plugin, which you are going to create by yourself.

Creation of the plugin

We have to admit that you may create a custom Gutenberg block using one of the default themes or your previously downloaded theme. However, in our example, we will create a custom plugin to work with it.

1. As a first step, you have to go to the “wp-content” folder > “plugins” folder.

2. Here create a new folder and name it the way you want to name your plugin. In this tutorial, the name of the folder will be “custom-gutenberg-blocks”.

3. After that, open the newly created folder and create a “custom.php” file right here. Open it and write down the following code. It will help to register the new plugin and load the JavaScript.

<?php function loadMyBlockFiles() { wp_enqueue_script( ‘my-test-text’, plugin_dir_url(__FILE__). ‘custom.js’, array(‘wp-blocks’, ‘wp-i18n’, ‘wp-editor’), true );} add_action(‘enqueue_block_editor_assets’, ‘loadMyBlockFiles’); ?>

view rawcustom.php hosted with ❤ by GitHub

4. In the same folder create a “custom.js” file. You have to call it the way you’ve set in the function. Here you can write your own JavaScript code.

Building a new block in JS within Gutenberg editor

In this part of our tutorial, we will show you how to create and register a JavaScript file to define the way, in which your block will be working. We will also set how it will look in the Gutenberg editor and frontend.

  • In order to create a custom Gutenberg block, we will use the “registerBlockType” method in your file. After that, you need to write down attributes in the brackets.
  • The first parameter will be your namespace and a block name. As a second parameter, you need to specify an array of everything, which will actually be an object.
  • The structure of a custom Gutenberg block is pretty simple. We’re gonna start by defining some built-in attributes, which are represented by the descriptions, title icons and the types of categories.
  • After that, some custom attributes need to be defined. It may be a specific text area or background image.
  • Then we need to specify some custom functions and the built-in functions.

Defining built-in attributes

Let’s start to build our first custom Gutenberg block! Firstly, we will write down all the built-in attributes.

  1. The easiest one is the “title” attribute. You can specify it the way you want. Specify a “description” as well.
  2. After that, define an “icon”. You can use dash icons by WordPress, which are built-in into the WP administration area. On the other hand, you copypaste an SVG picture.
  3. The last one is the “category”. It is necessary in order to list our custom block inside the WP administration area.

Set the custom attributes and built-in functions

Now we’re gonna create a custom “attributes” object, which will keep track of all our custom attributes. Let’s indicate its type. We will define it as “string”.

Leave the custom functions block blank because we don’t have any custom functions yet.

As a next step, we will define the built-in functions of the registerBlockType. There are actually just two of them: edit and save. However, they are a little bit complicated, so, for now, we are gonna leave it empty.

Appending the “edit” and “save” functions

  • First of all, let’s add a new function within the “edit” one, and name it the way we want. In our case, it’s “somename”.
  • Add the “event” and use props.setAttributes to establish a connection with the content and target it when it’s changed by the user who will input text.
  • The next step is to determine what method will return (what will be displayed in Gutenberg editor). To do it we’ll use JSX to build some code with react. You can use the Babel resource to build your code.
  • We’ll add a <div> and within it add a title we want to use for the widget and an input field with text type.
  • Connect it with props.attributes.content and use onChange to define the function that will be used. Than close the </div> tag.
  • Now you should copy the code generated on the right side and paste it right beside the “return”.

After all the job done your “custom.js” file will look like that:

https://gist.github.com/skrnagar/317b7e24bef9fc6e6256d5a1485da4fb

<script src=”https://gist.github.com/skrnagar/317b7e24bef9fc6e6256d5a1485da4fb.js"></script>

Congratulations! That is all you need for the backend. Now you may check how your new custom Gutenberg block will look.

We hope you liked our simple tutorial on how to create a new custom Gutenberg block with react or without react.

Thanks for reading. Follow me for my newsletter for more useful tutorials and instructions.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Sunil Nagar
Sunil Nagar

Written by Sunil Nagar

Blogger: #Artificial Intelligence #ML #Automation #Web Development #businessanalyst #ProductDevelpoment Follow: https://scriptedshadows.medium.com/

No responses yet

Write a response