WordPress block development has evolved significantly in recent years. By leveraging React JS and Server-Side Rendering (SSR), you can create powerful, dynamic blocks that are both fast and SEO-friendly. This tutorial will guide you through building a WordPress block that uses React JS for its front-end interactivity, integrates a settings panel for customization in the block editor, and uses SSR for server-side rendering to improve performance and SEO.
In this post, we’ll cover:
- Setting up a WordPress plugin to build a custom block
- Using React JS to create interactive block elements
- Integrating a settings panel for customization (using InspectorControls)
- Leveraging Server-Side Rendering (SSR) to handle block rendering on the server
- Using npm for JavaScript compilation and bundling
Let’s get started!
Prerequisites
Before you begin, you should have:
- A local WordPress development environment set up.
- Basic knowledge of React JS and WordPress block development.
- Node.js and npm installed on your computer.
- Familiarity with Server-Side Rendering (SSR) in WordPress.
Step 1: Set Up Your Plugin and Install npm Dependencies
First, we need to set up the WordPress plugin structure, initialize npm, and install necessary dependencies.
1.1 Create the Plugin Folder
Create a new folder for your plugin. For this example, we’ll name it react-counter-plugin
. Inside this folder, create the following structure:
react-counter-plugin/
├── src/
│ └── index.js
├── style.css
└── react-counter-plugin.php
1.2 Initialize npm
Open a terminal or command prompt in the plugin directory and run:
npm init -y
This will generate a package.json
file for your plugin.
1.3 Install WordPress Scripts
To manage JavaScript compilation and bundling, we’ll use @wordpress/scripts. This package provides helpful commands for building and running your JavaScript files in a WordPress environment.
Install @wordpress/scripts
as a development dependency:
npm install @wordpress/scripts --save-dev
1.4 Configure npm Scripts
Next, open the package.json
file and add the following script entries:
{
"name": "react-counter-plugin",
"version": "1.0.0",
"description": "A custom React block with SSR",
"scripts": {
"start": "wp-scripts start", // For development
"build": "wp-scripts build" // For production build
},
"devDependencies": {
"@wordpress/scripts": "^25.0.0"
}
}
npm start
: This will start a development server, watching for changes and automatically re-compiling the JavaScript.npm run build
: This command will create an optimized build of your plugin’s JavaScript files for production.
Step 2: Create the Block with React JS
Now, let’s move on to defining the block itself using React JS.
2.1 Create the Block in src/index.js
In the src
folder, create the index.js
file and add the following code to define the block’s functionality:
import { useState } from '@wordpress/element';
import { registerBlockType } from '@wordpress/blocks';
import { Button, TextControl } from '@wordpress/components';
import { __ } from '@wordpress/i18n'; // For translations
import { InspectorControls } from '@wordpress/block-editor'; // For settings panel
// Register the block
registerBlockType('react-counter-plugin/counter-block', {
title: __('React Counter Block', 'react-counter-plugin'),
icon: 'smiley', // Block icon
category: 'common', // Block category
attributes: {
counter: { type: 'number', default: 0 },
year: { type: 'string', default: new Date().getFullYear().toString() },
},
edit({ attributes, setAttributes }) {
const { counter, year } = attributes;
// Increment counter
const incrementCounter = () => {
setAttributes({ counter: counter + 1 });
};
// Update year from settings panel
const updateYear = (newYear) => {
setAttributes({ year: newYear });
};
return (
<div className="counter-block">
{/* Inspector Controls (Settings Panel) */}
<InspectorControls>
<TextControl
label={__('Year', 'react-counter-plugin')}
value={year}
onChange={updateYear}
type="number"
className="year-field"
/>
</InspectorControls>
<p>{__('Current Count: ', 'react-counter-plugin')} {counter}</p>
<Button isPrimary onClick={incrementCounter}>
{__('Increment Counter', 'react-counter-plugin')}
</Button>
<div>
<p>{__('Year:', 'react-counter-plugin')} {year}</p>
</div>
</div>
);
},
save() {
return null; // Content rendered server-side (SSR)
},
});
Step 3: Set Up Server-Side Rendering (SSR)
The key advantage of SSR is that it allows your block’s content to be rendered by WordPress on the server, which ensures better performance and SEO.
We will define a render callback in the PHP file to handle SSR. This will output the block’s HTML based on the block’s attributes.
3.1 Set Up the PHP File (react-counter-plugin.php
)
In the react-counter-plugin.php
file, register the block and set up the SSR callback function.
<?php
/**
* Plugin Name: React Counter Plugin
* Description: A custom React block with settings and SSR.
* Version: 1.0
* Author: Your Name
*/
defined( 'ABSPATH' ) || exit;
// Enqueue block scripts and styles
function react_counter_plugin_enqueue_assets() {
wp_enqueue_script(
'react-counter-block',
plugin_dir_url( __FILE__ ) . 'build/index.js',
array( 'wp-blocks', 'wp-element', 'wp-components', 'wp-editor', 'wp-i18n' ),
filemtime( plugin_dir_path( __FILE__ ) . 'build/index.js' ),
true
);
wp_enqueue_style(
'react-counter-plugin-style',
plugin_dir_url( __FILE__ ) . 'style.css',
array(),
filemtime( plugin_dir_path( __FILE__ ) . 'style.css' )
);
}
add_action( 'enqueue_block_editor_assets', 'react_counter_plugin_enqueue_assets' );
// Register the block with SSR support
function react_counter_plugin_register_block() {
register_block_type( 'react-counter-plugin/counter-block', array(
'render_callback' => 'react_counter_plugin_render_block',
'attributes' => array(
'counter' => array(
'type' => 'number',
'default' => 0,
),
'year' => array(
'type' => 'string',
'default' => (string) date('Y'),
),
),
) );
}
add_action( 'init', 'react_counter_plugin_register_block' );
// Callback function for SSR rendering
function react_counter_plugin_render_block( $attributes ) {
return sprintf(
'<div class="counter-block"><p>%s %d</p><p>%s %s</p></div>',
__('Current Count: ', 'react-counter-plugin'),
$attributes['counter'],
__('Year:', 'react-counter-plugin'),
$attributes['year']
);
}
Step 4: Build Your JavaScript and Test the Plugin
Once you’ve created the block, you can now build your JavaScript files using npm.
4.1 Run the Development Server
To start the development server, run:
npm start
This command will compile the JavaScript and start watching for changes. You can now test your block in the WordPress block editor.
4.2 Build for Production
Once you’re satisfied with your development, run:
npm run build
This will create an optimized version of your block for production use. The compiled files will be located in the build
directory, and you can deploy them to your WordPress site.
Step 5: Activate and Use the Block
- Activate the Plugin: Go to Plugins in your WordPress admin and activate the React Counter Plugin.
- Use the Block: Create or edit a post. You should see your custom block, React Counter Block, in the block editor. Add the block to your post and use the Year field in the settings panel to customize it.
Conclusion
In this tutorial, you’ve learned how to:
- Create a WordPress block using React JS.
- Add a settings panel to customize the block’s attributes in the editor.
- Implement SSR
Leave a Reply