Create a Wordpress Gutenberg-Block with all React-lifecycle methods in 5 Minutes
Tags: wordpress, react, gutenberg, javascript
Published: 2019-05-27 15:44:19


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](https://github.com/ahmadawais/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:

```shell
$ 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`](https://github.com/WordPress/gutenberg/tree/master/packages/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

```javascript
const { Component } = wp.element;
```

### Use `React.Component`

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

```javascript
edit: class extends Component { … }
```

Add the `constructor`-function …

```javascript
//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 …
```javascript
// 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.

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

__That's it.__

## Sourcecode
- Boilerplate code from `create-guten-block` {% gist https://gist.github.com/martinkr/48acc9d564040365df4172df753c3aaf %}
- The final code as `React.Component` {% gist https://gist.github.com/martinkr/d47d48f81d39f911b7294af46f6019c6 %}



---

Follow me on [Twitter: @martinkr](http://twitter.com/_martinkr) and consider to [buy me a coffee](https://www.buymeacoffee.com/martinkr)