Building a Gutenberg Block

After completing Zac Gordon’s wonderful Gutenberg Development Course, I wanted to try building my own block. It was more difficult than I expected, but a great learning experience.

I added a “List Subpages” block to my BE Subpages Widget plugin (code here). This lets you select a page and dynamically lists all its subpages.

The biggest hurdle is my lack of knowledge of modern JavaScript development. I’m a theme and plugin developer, so I’m comfortable with PHP and frontend markup. I use a bit of jQuery in theme development, but nothing special.

There was a lot of copy/pasting pieces from existing blocks while I tried to figure out the proper syntax to implement what I want. I’m sure this code could be written better if I knew what I was doing.

Getting Started

I followed the example code from the Gutenberg Development Course to setup the plugin initially. You could also use the create-guten-block tool or the wp cli command wp scaffold block.

In terminal, run npm install in the plugin’s directory. Then run npm run dev, which will monitor the files for changes and recompile the resulting CSS/JS into the assets directory.

In the main plugin file I’m enqueuing the editor-specific Javascript using the enqueue_block_editor_assets hook. If my block required its own styling or JS, I’d also enqueue block-specific CSS and JS using enqueue_block_assets hook, which applies to both the editor and frontend, ensuring the block looks the same in both places.

Starting the block

In the block’s index.js file, use registerBlockType() to create a block (example). You specify a unique name, some basic parameters, and two functions: edit and save.

The edit function is what’s rendered in the Gutenberg editor. When the block is in focus, I’m displaying a dropdown menu, and when the block is out of focus I’m displaying the actual subpages list.

The save function is saved into the post content and is shown on the frontend. Since my block is outputting dynamic content, my save function is empty and I created a PHP callback function to handle the output, similar to a shortcode.

This is one complaint I have about Gutenberg.  All dynamic elements need to be implemented twice: once in JS for the edit() function so it’s visible in editor, and again in PHP for frontend render. You’ll need to be careful to keep your WP_Query returning the same results as your JavaScript REST API Query.

Gutenberg is readable and reusable

Gutenberg’s code is very clean and logical. Everything is broken down into small, single-purpose files. Reusable components are accessible from global variables.

In my plugin I wanted a dropdown menu with a hierarchical page listing.  I found an existing area of Gutenberg that already did this – the “page parent” dropdown in the Page Attributes section.

In the parent.js file in editor/components/page-attributes, they’re using <TermTreeSelect> to create this hierarchical select menu (see here). At the top of the file you’ll see they are importing that component from another file:

import { TermTreeSelect } from '@wordpress/blocks';

You can’t copy this line directly, but you can use something similar:

const { TermTreeSelect } = wp.blocks;

I used this approach to find all the pieces I needed and import them all. I also kept my code simple and readable by breaking my functionality into separate files.

Querying Posts

You can use withAPIData() to query for data using the REST API. The examples I found in Gutenberg used a constant like applyWithAPIData to build the query, then applies it to your component on export. You can then access the JSON result of that query by using whatever variable you returned in the constant (in this case, pages).

See the REST API Handbook for more information on querying.

Lots to learn

It truly is time to “Learn Javascript Deeply” to keep up with future WordPress development. To that end, I’m:

  • Reading Eloquent Javascript
  • Taking Wes Bos’ courses Javascript30 (free), ES6 for Everyone, and React for Beginners.
  • Keeping up with Gutenberg development. I’m reading all the issues and pull requests to follow what’s changing and improve my understanding of the underlying code.
  • Contribute where I can. Here’s my first bug report and patch.
  • While building client sites, find elements to build as Gutenberg blocks in my free time. Implementing these real-world examples will help prepare me for when I’m actually building client sites with Gutenberg.

We’re still many months away from Gutenberg merging into core. But if you’re like me, it’s going to take that long to become technically competent in modern JavaScript and comfortable building websites using Gutenberg.

Now is the perfect time to start learning.

Tutorial

Receive New Posts by Email

Comments

  1. Hi bill thanks for your article.
    I just have one question
    I wonder how stringify works with array. I mean when I have

    const query = stringify( {
    context: ‘edit’,
    per_page: 100,
    orderby: ‘menu_order’,
    order: ‘asc’,
    _fields: [ ‘id’, ‘parent’, ‘title’ ],
    } );

    I get context=edit&per_page=100&orderby=menu_order&order=asc but then how do it work with _fields: [ ‘id’, ‘parent’, ‘title’ ] ?

    1. I console.log‘d the resulting string and it is: “/wp/v2/pages?per_page=100&parent=80&orderby=menu_order&order=asc&_fields=id%2Cparent%2Ctitle”

      It looks like the array items are simply separated with commas (%2C = comma).

      1. Looking since two weeks now, all similar block examples I can find only list maximum 100 results.

        Do you know how to change const pages = get( this.props.pages, ‘data’, [] ); to get the number of real results and also the remaining results?

        Thank you if you can enhance your tutorial. I like your writing, it is much clearer and understandable as other tutorial.

          1. Thank you, but I am looking for posts 1-100 and 101-200 together in one result variable. Will keep looking..

  2. Thank you. There is a parameter ‘page’ as well, maybe the request can be called more times after each other but I dont know how to put this in the get() function and how to find how many pages.

    There must be a way, so many use cases for blocks have more than 100 results and writing own endpoint for every block sounds overkill.

    1. You could just run two API queries, and on the second one add &offset=100. That will get you posts 101 – 200.

      As I mentioned in the post, I’m not very experienced with JavaScript so I’m not sure the best way to write that. You could probably duplicate the whole `applyWithAPIData` constant (ex: `applyWithAPIData2`), return a different property (ex: `pages_2`), then in the render function combine the two arrays. But I’m sure there’s a better way.

  3. Hey Bill, I’ve completed the same course from Zac Gordon and very exciting to work on Gutenberg for my plugins and themes. Thanks a lot for sharing your experience. It’s really inspiring.

  4. Hi Bill
    Thanks for your article.
    I have one question about: const pageItems = get( pages, ‘data’, [] );
    What are you trying to do here? What is ‘data’ and the empty array

    1. At the bottom, applyWithAPIData builds the WP REST API query and returns it as pages (see here).

      We then pass that API query url to SelectSubpages here.

      So inside SelectSubpages, when I call get( pages ), I’m doing the actual API query using the “pages” query URL generated by applyWithAPIData.

      As for the ‘data’ and empty array part, I don’t recall exactly. I think I copied the general structure from an existing block in Gutenberg and it probably had that (example). I’m guessing the second parameter says what we want (give us the data), and the third parameter is a default value to use if it’s empty or an error.

Leave a comment