How to create a Gutenberg background shape generate

In this tutorial, we’re going to create a background shape generator for Gutenberg, this shape generator will specifically work on the core Gutenberg cover block.

Pre-requisites

  1. Gutenberg Block Filters: Some basic knowledge about Gutenberg block filters.
  2. React.js: Some basic knowledge about react.js.
  3. Gutenberg BlocksSome basic knowledge about Gutenberg blocks.

End Result

Gutenberg background shape generator overview

It’s always better to know upfront what a tutorial is going to achieve at the end of the day.

User Experience

When developing something, I personally feel that it’s crucial to plan user experience before actually developing something, User experience is basically planning how a user will interact and use our product.

In our case, the user experience is pretty simple, here’s how a user can change background shapes (see workflow below):

1. User inserts a cover block

2. User clicks on the toolbar icon to generate a new shape

Getting Started

Now that we’ve covered all the basics, let’s jump right into actually creating this extension. Please use this starter template “CakeWP/gutenberg-extension-starter-template” for quickly creating Gutenberg-based plugins.

Extending the Gutenberg cover block

Let’s start by extending the core gutenberg cover block with an additional toolbar button which won’t do anything yet.

// src/index.js
import { __ } from '@wordpress/i18n';
import { addFilter } from '@wordpress/hooks';
import { Fragment } from '@wordpress/element';
import { BlockControls } from '@wordpress/block-editor';
import { createHigherOrderComponent } from '@wordpress/compose';
import { ToolbarGroup, ToolbarButton } from '@wordpress/components';
// src/index.js
const withShapeGenerator = createHigherOrderComponent( ( BlockEdit ) => {
    return ( props ) => {

        if ( props.name !== "core/cover" ) {
            return <BlockEdit {...props} />
        }

        return (
            <Fragment>
                <BlockEdit { ...props } />
                <BlockControls>
                    <ToolbarGroup>
                        <ToolbarButton 
                            showTooltip
                            icon="update"
                            onClick={updateBackgroundShape}
                            label={__('Update shape', 'gutenberghub-random-background')}
                        />
                    </ToolbarGroup>
                </BlockControls>
            </Fragment>
        );
    };
}, 'withInspectorControl' );
 
addFilter(
    'editor.BlockEdit',
    'my-plugin/with-inspector-controls',
    withShapeGenerator
);

Now, we should have a new button in the block toolbar for Gutenberg cover block.

new toolbar button

Generating Background Shapes

Please download and save the following curated shapes collected in the “src” directory of your extension.

Attaching click listener

Now, let’s attach a click listener on the toolbar button that we’ve just added above.

// src/index.js
const withShapeGenerator = createHigherOrderComponent( ( BlockEdit ) => {
    return ( props ) => {

        if ( props.name !== "core/cover" ) {
            return <BlockEdit {...props} />
        }

        const updateBackgroundShape = () => {
            console.log('Generate a new shape');
        }

        return (
            <Fragment>
                <BlockEdit { ...props } />
                <BlockControls>
                    <ToolbarGroup>
                        <ToolbarButton 
                            showTooltip
                            icon="update"
                            label={__('Update shape', 'gutenberghub-random-background')}
                            onClick={updateBackgroundShape}
                        />
                    </ToolbarGroup>
                </BlockControls>
            </Fragment>
        );
    };
}, 'withInspectorControl' );

We’ve just added an empty click listener above that simply does a console.log when clicked.

initial click listener

Generating random background shapes

Let’s update the click listener to actually generate random background shapes

import shapes from './shapes.json'
const updateBackgroundShape = () => {
    const newRandomShape = shapes[Math.floor(Math.random() * shapes.length)];
    const encodedShape = `data:image/svg+xml,` + encodeURIComponent(newRandomShape);
    props.setAttributes({ url: encodedShape });
}

After updating the listener, we can now successfully generate random background shapes.

Wrapping Up

Let’s wrap this tutorial here. Here are some tasks for you

  1. Try implementing this in the core gutenberg group block.
  2. Extend “shapes.json” and add your own background shapes.
  3. Try adding a new option in inspector controls that allows user to specifically select their desired background shape.

If you have any queries regarding this tutorial. Please feel free to comment down or join our Gutenberg Community on Facebook.

💌

Unlock Exclusive Perks: Join Our VIP Subscriber Club Today!

Subscribe for special promotions, offers, freebies, and the latest updates and news – all exclusively for our VIPs. Don’t miss out, join now! 🌟💌🎁

We won’t send you spam, we promise.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Join the All Access Club

Your All-Inclusive Pass to Premium WordPress Products.