WordPress Gutenberg

Gutenberg tutorial, how to program your first block

In all programming languages ​​there is always a "hello, world!", the typical "hello world!«. And when it comes to programming blocks, it could be translated into creating a block that shows a text that you enter. This is the reason why we are going to program a simple but effective text block.

Creation of the block

Based on what was explained in the entry About preparing a workspace, let's start configuring the block. For this, we will first have to open the folder brok guten block and open a terminal in it. Then we will execute the command npm run create block-nameWhere block-name is the name of the block you want to create.

With this, we will go to the folder src/block-name and, once there, we now have to talk about some points. Let's explain the basic structure of a block, very important to learn to program them
????. Every block normally contains at least the following structure:

The block.js file, public content

The file block.js unites the entire structure by unifying the code and configuring the block. Also, specify its attributes, the registerGutenBlock method, and the content that readers will see of the block. From the above we will create separate entries for the tutorial due to its complexity.

In this file, we will have to fill in the variable atrs with an attribute to store the content of a paragraph. By simply adding this code, we can generate an attribute that stores the text that we enter in the paragraph:

/**
 * Atributos del bloque
 */

// Pasamos de esto
const attrs = {
  mwmAtributos, //Atributos de componentes internos de mowomo
};

// A esto otro
const attrs = {
  mwmAtributos,  //Atributos de componentes internos de mowomo
  parrafo: {
    type: "string",
    source: "html",
    selector: ".parrafo",
    default: "Texto del párrafo"
  }
};

Then in the function save (), we will change several points. First, we'll speed up access to attributes by creating intermediary variables between them and the save() function:

// Pasamos de esta línea
const { } = attributes;

// A esta otra
const { parrafo } = attributes;

We'll end up creating inside the return and the inside a paragraph whose value will be that of the attribute paragraph. For this we will use the component RichText.Content, which will display the content picked up by another RichText.

/**
 * Contenido del front-end del bloque
 */
return (
  <Fragment>
    <div className={"bloque-parrafo"}>
      <RichText.Content
        tagName={"p"}
        className={"parrafo"}
        value={parrafo}
      />
    </div>
  </Fragment>
);

So that, in the end, this code remains in the save() function:

save(props) {
    /**
     * Variables
     */
    const { attributes } = props;
    const { parrafo } = attributes;

    const estilos = {};

    /**
     * Funcionalidades
     */

    /**
     * Contenido del front-end del bloque
     */
    return (
      <Fragment>
        <div className={"bloque-parrafo"}>
          <RichText.Content
            tagName={"p"}
            className={"parrafo"}
            value={parrafo}
          />
        </div>
      </Fragment>
    );
  }

As a result, we will already have the public part of the block programmed, so we still have the editor part. Come on, we are already halfway through the process, there is nothing left to finish.

The editor.js file, editor content

Let's start by opening the file editor.js inside the folder components. This file will be a component of react, which we will talk about in another entry, and it will show us the part of the block in the WordPress admin.

We will do everything inside the method render() from the file. We will begin, then, by adding the attribute paragraph to the method variables taken from the attributes. With this, we will speed up the work with the attribute.

// Pasamos de esto
const { } = attributes;

// A esto
const { parrafo } = attributes;

Then, we will continue creating an input, which is nothing more than a text entry, inside the return. To do this, we will use the component RichText to collect the code that we type on the screen:

// Pasamos de esto
<Fragment>
  <Controles {...this.props} />
  <Inspector {...this.props} />
  <div className={"bloque-parrafo"}>
    // Insertar el componente aquí
  </div>
</Fragment>

// A esto otro
<Fragment>
  <Controles {...this.props} />
  <Inspector {...this.props} />
  <div className={"bloque-parrafo"}>
    <RichText
      tagName={"p"}
      className={"parrafo"}
      value={parrafo}
      onChange={valor => setAttributes({parrafo: valor})}
      placeholder={__("Introduce un texto")}
    />
  </div>
</Fragment>

We would end up with all this code:

render() {
  /**
   * Variables
   */
  const { attributes } = this.props;
  const { parrafo } = attributes;

  const estilos = {};
   /**
   * Funcionalidades
   */

  /**
   * Contenido del editor
   */

  return (
    <Fragment>
      <Controles {...this.props} />
      <Inspector {...this.props} />
      <div className={"bloque-parrafo"}>
        <RichText
          tagName={"p"}
          className={"parrafo"}
          value={parrafo}
          onChange={valor => setAttributes({ parrafo: valor })}
          placeholder={__("Introduce un texto")}
        />
      </div>
    </Fragment>
  );
}

The RichText component uses the internal attribute we change to convert the entered text value inside external attribute paragraph by setAttributes. Then, it displays the value collected using the internal attribute value.

Once this is done, we will have a code input ready from the editor for our block to save text.

Using the block

Now we will execute the command npm start from the root of the project so that all code is compiled into a stable plugin. Simply, by entering a post or a page and looking for our block, we could use it.

With this we finish the article on how to program your first block in Gutenberg. It may have been a little complicated or you didn't understand everything, but cheer up, little by little you'll end up making big blocks. You know, if you liked the article and you have learned something new, share it and write a comment with your experience. Until the next article of the tutorial, a greeting ✋.

¡Subscribe to our newsletter and receive our offers, news and discounts directly to your email!