This is the third part of a WordPress Gutenberg Blocks series. You can see Part 1 and part 2.  The finished repo for this tutorial is located here.

We’ve created a simple block that allows a user to edit an h2 element in a truly WYSIWYG style.  We’ve talked about how WordPress Gutenberg does attributes and how that enables us to create interactive elements.

Now, it’s time to include CSS in our block.  The Gutenberg editor allows us to enqueue two “new” styles: the editor styles and the view styles.  So there are really three stylesheets you should be thinking about when you are developing a block

editor.cssview.cssstyle.css
A css file only used in the editorA css file that is used both in the editor and in the viewThe regular styles file that is loaded in a theme for the view only
Added to WordPress using the enqueue_block_editor_assets hookAdded to WordPress using the enqueue_block_assets hookAdded either by default if you used the default style.css in the theme folder, or by using the function wp_enqueue_style in your theme folder
Is used specifically to style aspects of the block that deal with editingUsed for styling that should be present for overall layout and presentationUsed for specific theme styles and looks
Example: When you hover over a picture in the gallery while editing, a “delete this picture” button appears.  This a case where it is editor-specificExample: In a gallery you want the pictures to be laid out 3-up with a 16 px gutterExample, specific colors, fonts, heading styles, etc…

And keep in mind that the way I think about it is partially a matter of preference and there are many grey areas.  I have heard on many occasions, though that stuff in the theme are for presentation, stuff in a plugin are for functionality.  Editor.css and view.css are in the plugin, so technically they should be solely for functionality… (shrug).

Adding Gutenberg block styles through WordPress hooks

In the ‘src’ file add ‘view.css’.  Since our “My First RichText Block!” is actually an h2 element, let’s add an h2 style to see that our styles are working:

h2 {
    background: orange;
    color: white;
}

So now that we have our ugly styles, how do we let WordPress know to include them?  We return to our firstgutyblocks.php file and enqueue the file.  Add the following to the bottom of this file:

function firstgutyblocks_hello_world_assets() {
    wp_enqueue_style(
		'firstgutyblocks/hello-world',
        plugins_url( 'src/view.css', __FILE__ ),
        array( 'wp-blocks' )
	);
}
add_action( 'enqueue_block_assets', 'firstgutyblocks_hello_world_assets' );

Now you should see those styles in the editor and the view.  But yet again, there’s another problem!

Hello world block with styling that is also styling every other h2 in the Gutenberg editor...

We are affecting things outside of our block because our CSS is not targeting our block class.  So let’s talk about how to handle classes in our Gutenberg Block markup.

Controlling class names with Gutenberg Blocks

If you inspect our block as it is, there actually is a class being automatically applied to our block:

Gutenberg will automatically place ‘wp-block-{name used to register block in js}’ on the containing element.  This is all well and good if we want to target just that outer container, so let’s change our css:

.wp-block-firstgutyblocks-hello-world {
    background: orange;
    color: white;
}

Now, we should see the styles being only applied to our block.  Sweet, sweet victory.

But, let’s say, you wanted to have an h2 inside of a div, and that outer div had the classname?  We can start manually placing the classname by changing our editing and saving methods.  The key is that Gutenberg gives you the block class name in the props it send edit() and save().  The prop you will now use is “className”

edit(props) {

    const { 
        setAttributes, 
        attributes,
        className // The class name as a string!
    } = props;

    function onTextChange(changes) {
        setAttributes({
            textString: changes
        });
    }

    return (
        // We've added a container div
        // and we're placing our styles on that manually
        <div className={className}>
            <RichText
                tagName="h2"
                value={attributes.textString}
                onChange={onTextChange}
                placeholder="Enter your text here!"
                />
        </div>
    );
},

save(props) {

    const { attributes, className } = props;

    return (
        <div className={className}>
            <h2>{attributes.textString}</h2>
        </div>
    );
}

One thing is different now, though.  If you load up the block in the editor again, you will have an orange background but black text.  If you update, you will have an orange background and white text.

The reason for this is that you aren’t targeting the h2 color specifically, and the Gutenberg editor has styles that color headings black.

So here’s a suggestion for how to fix that:

.wp-block-firstgutyblocks-hello-world {
    background: orange;
}
.wp-block-firstgutyblocks-hello-world h2 {
    color: white;
}

Enqueueing editor-specific styles

The stylesheet we just added will always be used in the editor and in the view.  Sometimes, though, there will be elements that are used in the editor only that need to be styled.  So how to we enqueue those stylesheets?

Let’s create a stylesheet named ‘editor.css’ with the following:

.wp-block-firstgutyblocks-hello-world {
    position: relative;
}

.wp-block-firstgutyblocks-hello-world:before {
    position: absolute;
    top: 0;
    right: 1em;
    content: 'Editor mode!';
    color: navy;
    font-weight: bolder;
}

This will place a pseudo-element only when we’re editing the block.  In our php file we will also have to edit firstgutyblocks_hello_world_editor_assests():

function firstgutyblocks_hello_world_editor_assets() {
    wp_enqueue_script(
        'firstgutyblocks/hello-world',
        plugins_url( 'build/index.build.js', __FILE__ ),
        array( 'wp-blocks', 'wp-element' )
    );
    wp_enqueue_style(
		'firstgutyblocks/hello-world-editor-style',
        plugins_url( 'src/editor.css', __FILE__ ),
        array( 'wp-edit-blocks' )
	);
};

add_action( 'enqueue_block_editor_assets', 'firstgutyblocks_hello_world_editor_assets');

It is important to name wp_enqueue_style differently (in our case ‘hello-world-editor-style’) to make sure there aren’t conflicts in enqueuing.  Also, be careful to change the dependency from ‘wp-blocks’ to ‘wp-edit-blocks’.

Hopefully you will see:

Hello word block with "editor mode" styling

So when is this useful?  I’ve used it a couple times where elements I created elments that only appear in the editor.  For example, when I created a gallery, I had buttons that allowed the editor to move images left/right or remove them.  These buttons need some sort of love and styling, but only occur in the editor.

Recap

We’ve gone over how to enqueue view and editor stylesheets.  We also used the className prop to manually place classNames within our blocks.

Next up we need to look at RichText more in depth and include InspectorControls and an editing Toolbar.

Prerequisites:

Gutenberg Blocks may seem overwhelming, but I’m hoping to clear away just enough details so that we can see what’s going on at the heart of this new editor.  I’m assuming that:

  • You’re familiar with some build processes with babel
  • You’ve done enough React to be familiar with JSX
  • You’re primarily Javascript/html/css focused.

Outline:

Here are the steps we’ll take to get a block loaded in the Gutenberg editor.  We plan on making a single block with pre-rendered text.  (No interactivity, CSS, fancy stuff yet)

  1. Set up WordPress and a folder structure
  2. Create a build process with webpack
  3. Call the block’s javascript into the editor with php
  4. Register a block with javascript

To see the finished product, you can see the repo here

WordPress Gutenberg and folder structure:

Make sure that you have installed and activated the Gutenberg plugin.

I use local by flywheel to quickly spin up instances of WordPress. Whichever way you choose to set up your WordPress, you’ll need a folder inside of your plugins folder with your plugin title.

Inside this firstgutyblocks folder we will have a php file that I’ve named “firstgutyblocks.php”.  This will contain the plugin information.  You’ll need to include these comments so WordPress knows what to do with this file:

<?php
/**
 * Plugin Name: First Guty Blocks
 * Description: Our first Gutenberg Blocks!
 * Version: 1.0.0
 * Author: Jim Schofield
 *
 * @package firstgutyblocks
 */

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

Before moving on, go into wp-admin and activate our plugin!

Set up the Gutenberg build process

Time to set up Webpack

Webpack’s role is to transpile our JSX into friendly javascript.  If this is unfamiliar to you, take a look here and check out babel.  There are ways to write code in vanilla javascript instead, but I don’t recommend it.  JSX is the bread and butter of React applications, and if you look at the source code of Gutenberg, that’s about all you’ll see.  So it’s best to get comfy with it 🙂  It’ll save you time in the long run.

In the terminal, go to your firstgutyblocks folder and init npm.

npm init

It will ask you to fill in information like project names, etc., but you can just go with defaults (just keep pressing enter).  Then, install some dependencies:

npm install --save-dev webpack webpack-cli babel-core babel-loader babel-preset-env babel-preset-react

That’s a lot… so here’s the what and why for all of those things:

  • webpack – our asset bundler/task runner of choice today
  • webpack-cli – allows us to use some commands in the command line that are useful
  • babel-core – the thing that will transform our bleeding edge javascript into plain ol javascript
  • babel-loader –  allows us to use babel inside of webpack
  • babel-preset-env and babel-preset-react – basically the rules babel follows to transform our javascript

So now that we have all of those dependencies, let’s start making webpack work…

We’ll need to create a webpack.config.js file in the firstgutyblocks folder and configure it to build what we want, where we want, how we want:

// node module that let's us do file system stuffs...
const path = require('path');

// Webpack expects an exported object with all the configurations, so we export an object here
module.exports = {
    entry: './src/index.js', // Where to find our main js
    output: {
        // where we want our built file to go to and be named
        // I name it index.build.js so I keep index files separate
        filename: 'index.build.js',
        // we're going to put our built file in a './build/' folder
        path: path.resolve(__dirname, 'build')
    }, 
    module: {
        rules: [
            { 
                // basically tells webpack to use babel with the correct presets
                test: /\.js$/,
                loader: 'babel-loader',
                query: {
                    presets: ['babel-preset-env', 'babel-preset-react']
                }
            }
        ]
    },
    // Webpack yells at you if you don't choose a mode...
    mode: 'development'
}

Now… we’re about to actually run webpack.

First, let’s go to our package.json and add the following to our “scripts” key:

...
"scripts": {
    "build": "webpack"
    "test": "echo \"Error: no test specified\" && exit 1"
}
...

This is a convenience thing- to run a build we type “npm run build”.  If you do it right now, you will see an error because we don’t have a javascript file yet…

So let’s make a “src” folder and create an “index.js” in that.  I’m going to add this code to said index file:

const message = <h1>Test JSX!</h1>;
console.log("Hello World!");

And now if you do “npm run build” again you should have a nice, pleasant, build message!

So what’s with the javascript that I added?  Well, first, I want a console log that’s run when the script is loaded letting me know when the javascript is loaded and working correctly in the editor.  Second, I want to make sure that the transpiling is taking place when I run webpack.  So if I try to use jsx as I am on the first line, it will fail when I try to run webpack if something’s not configured or installed.

So far, we have webpack building our javascript into a file in the build folder, and our plugin folder should look like this:

Calling the javascript in php

Now, we actually want WordPress to take that javascript and load it when we open up the shiny new Gutenberg editor.  So we go back to the plugin file and add a function that’s called in a new shiny WordPress hook ‘enqueue_block_editor_assets’.  Basically, we want WordPress to know about our new Gutenberg block and where the javascript file is located.  Let’s add to our ‘firstgutyblocks.php’ file…

/* this function name I believe is arbitrary, but I 
* generally see  people follow 
* {namespace}_{blockname}_editor_assets as a 
* naming convention
*/
function firstgutyblocks_hello_world_editor_assets() {
    wp_enqueue_script(
        // the name - also generally {namespace/blockname}
        'firstgutyblocks/hello-world',
        // where the javscript is located
        plugins_url( 'build/index.build.js', __FILE__ ),
        // and dependencies WordPress needs to serve up for us
        // you must have these two for the most basic block
        array( 'wp-blocks', 'wp-element' )
    );
};

// and then, we actually have the function run when the editor loads...
add_action( 'enqueue_block_editor_assets', 'firstgutyblocks_hello_world_editor_assets' );

OKAY.  NOW we can actually log in to WordPress and open a page or a post.  If all goes well, you will now be rewarded with a “A Guty Block is Present!” console log when the editor starts up.  You’ll need to reload the editor if it’s already open.

So we haven’t actually made a block or added it to the editor yet.  Most of the battle has been fought, we’re almost there…

Register our block in javascript

We have a process to get Javascript building.  We have our one javascript file loading when the editor loads.  Now it’s actually time to create the block in javascript!

Let’s go back to the index.js file and remove the work before.  First, let’s get what we need to register a block:

const { registerBlockType} = wp.blocks;
// using destructuring to basically do:
// const registerBlockType = wp.blocks.registerBlockType

wp.blocks is provided for us on the window already.  We need to retrieve this function to register our block:

const { registerBlockType} = wp.blocks;

registerBlockType('firstgutyblocks/hello-world', { 
        // We put the Guty config stuff here
    }
);

The method registerBlockType takes two arguments.  The first is the block is the block’s unique name.  The second a config object.  This config object is where the React part takes over.  Let’s fill in that object now.

const { registerBlockType} = wp.blocks;

registerBlockType('firstgutyblocks/hello-world',{ 
        // We put the Guty config stuff here
        title: 'My First Guty Block!', //Title seen in the editor for the block
        icon: 'smiley', //using WordPress' dashboard icons
        category: 'common',

        // edit is basically the 'render' function for your block.  
        // It can be a live react app inside the editor.
        edit() {
            return <h1>Hello Editor!</h1>;
        },

        // save is the 'render' function, but it's used to generate a static html 
        // string, and it is not a live react app.
        save() {
            return <h1>Hello World!</h1>;
        }
    }
);`

When you load the editor, you should be able to select “My First Guty Block!”  You should then see a static h1 element saying “Hello Editor!”  If you publish, you would see a static h1 element on the page saying “Hello World!”

Review

We’ve set up a WordPress plugin to register a Gutenberg block and load this block in the editor.  We’ve set up a webpack build process to build all the files we need.

Although this static example is not so impressive to look at, I promise that there are some exciting things possible in this new editor.  I plan to write some more articles on how to make make interactive and truly WYSIWYG blocks, adding CSS, and doing advanced things like API calls and rendering react applications on the front end.

In the meantime, I have a repo of some general blocks I’ve been playing around with if you’re interested.

Check out part 2: Creating an editable field