DEV Community

loading...

Create a Wordpress Gutenberg-Block with all React-lifecycle methods in 5 Minutes

martinkr profile image martin krause ・3 min read

A few weeks ago, I was creating a custom Gutenberg-Block. I needed to query an API to supply the editor with real-time data.
Since WordPress Gutenberg-Blocks are build on top of React, I wanted to use componentDidMount and subsequently the complete React-Lifecycle.
Finally, I needed only a few minor modifications to get the complete React functionality in my Gutenberg-Block.

Let me show you the fastest way to unlock the power of React.

Prologue: Gutenberg & Gutenberg-Blocks

Starting with WordPress 5.0, Gutenberg is "just the new editor". Alas, it's meant to redefine WordPress's complete publishing experience.

Instead of the crude mixture of custom HTML, "WordPress-shortcodes" and "magic embeds" of current WordPress-Pages, every element will be a "Gutenberg-Block".

One "Gutenberg-Block" contains one feature, one interaction and provides one single user-interface. The user does not need any technical knowledge to create a page with Gutenberg-Blocks.

Gutenberg already comes with a set of basic blocks such as paragraph, image, blockquote or recent blocks, etc. and you can create custom Blocks with JavaScript, HTML, CSS and PHP.

Create the Gutenberg-Block

Gutenberg uses a modern, React-based front end stack. The foundation is wp.element which is a thin abstraction layer atop React. Gutenberg uses it to create the Blocks and static HTML for persisting the content. The "editor-view" uses the React component which saves static, serialised HTML. The "visitor" receives the saved static HTML instead of the React component.

The simplest way to create a custom Gutenberg-Block is to use a boilerplate. Let me introduce you to create-guten-block.

create-guten-block is zero configuration dev-toolkit (#0CJS) to develop WordPress Gutenberg blocks in a matter of minutes without configuring React, webpack, ES6/7/8/Next, ESLint, Babel, etc.

… with create-guten-block

Let's create a simple "boilerplate" Gutenberg-Block which we will modify to use the desired React-lifecycle methods.

Open up your terminal and create the boilerplate code from create-guten-block by typing:

$ cd wp-content/plugins/
$ npx create-guten-block React-lifecycle-block
$ cd React-lifecycle-block
$ npm start

Convert it into a React.Component

Now, we need to make two modifications:

Import React.Component

wp.element is Gutenberg's thin abstraction layer atop React. It provides an API for leveraging most of React's functionality in any custom Gutenberg-Block.

First, import the React.Component from wp.element at the top of your file

const { Component } = wp.element;

Use React.Component

Now, we convert the edit-function into a React.Component using the Com

edit: class extends Component {  }

Add the constructor-function …

//standard constructor for a React.Component
constructor() {
    super(...arguments);
    console.log(this.props.name, ": constructor()");
    // example how to bind `this` to the current component for our callbacks
    this.onChangeContent = this.onChangeContent.bind(this);
    // a place for the state
    this.state = {};
}

… and the desired lifecycle functions to the edit-function …

// componentDidMount() is invoked immediately after a component is mounted
// https://Reactjs.org/docs/React-component.html#componentdidmount
componentDidMount() {
    console.log(this.props.name, ": componentDidMount()");
}
// componentDidUpdate() is invoked immediately after updating occurs
// https://Reactjs.org/docs/React-component.html#componentdidmount
componentDidUpdate() {
    console.log(this.props.name, ": componentDidUpdate()");
}
// componentWillUnmount() is invoked immediately before a component is unmounted and destroyed
// https://Reactjs.org/docs/React-component.html#componentdidmount
componentWillUnmount() {
    console.log(this.props.name, ": componentWillUnmount()");
}

… and finally we need to call render before returning the HTML-String from the edit-function.

render() {
    return (<div className={this.props.className}></div>);
}

That's it.

Sourcecode

  • Boilerplate code from create-guten-block
  • The final code as React.Component


Discussion (5)

pic
Editor guide
Collapse
mrstevedev profile image
Steve Pulido

Wow great article. I was trying to do this in my Gutenberg block for like 3 weeks. My problem was that I had my constructor() and other Lifecycle methods outside of the edit:(). Which is correct for React but not within the context of Gutenberg. I couldn't understand what was wrong but this clears it up and makes sense now. Thank you!

Collapse
martinkr profile image
martin krause Author

Glad I could help :)

Collapse
jameskendy profile image
jameskendy

Thanks for sharing this tutorial. Can you also please guide me how can I create a block template? I am doing the same using this resource wpitech.com/create-wordpress-guten... but it’s giving an error and I am having some programming lines in front end. This is the code
add_action( ‘init’, function() {
$args = array(
‘public’ => true,
‘label’ => ‘News’,
‘show_in_rest’ => true,
‘template_lock’ => ‘all’,
‘template’ => array(
array( ‘core/paragraph’, array(
‘placeholder’ => ‘Breaking News’,

Collapse
rayosdev profile image
rayosdev

This is great, but I am having problems accessing attributes for the block, any suggestions?

Collapse
rayosdev profile image
rayosdev

found my solution by looking at this project as a reference

github.com/bigbite/gutenberg-postl...