How to Create Custom WordPress Blocks with React: Complete Developer Guide

Master Custom WordPress Block Development with React

WordPress Gutenberg blocks have revolutionized content creation, and with React at its core, developers can build powerful, interactive custom blocks. This comprehensive guide will walk you through creating custom WordPress blocks from scratch.

1. Setting Up Your Development Environment

First, ensure you have the WordPress development environment ready:

npm install @wordpress/scripts @wordpress/blocks @wordpress/element @wordpress/components --save-dev

2. Create the Block Registration File

Start by creating your block’s main JavaScript file:

import { registerBlockType } from '@wordpress/blocks';
import { useBlockProps } from '@wordpress/block-editor';
import { __ } from '@wordpress/i18n';

registerBlockType('my-plugin/custom-block', {
    title: __('Custom Block', 'my-plugin'),
    description: __('A custom block built with React', 'my-plugin'),
    category: 'widgets',
    icon: 'smiley',
    supports: {
        html: false,
    },
    edit: EditComponent,
    save: SaveComponent,
});

3. Building the Edit Component

Create the editor interface using React hooks and WordPress components:

import { InspectorControls, useBlockProps } from '@wordpress/block-editor';
import { PanelBody, TextControl, ToggleControl } from '@wordpress/components';

function EditComponent({ attributes, setAttributes }) {
    const { title, showBorder } = attributes;
    const blockProps = useBlockProps();

    return (
        <>
            
                
                     setAttributes({ title: value })}
                    />
                     setAttributes({ showBorder: value })}
                    />
                
            
            

{title || __('Enter your title...', 'my-plugin')}

); }

4. Creating the Save Component

Define how your block renders on the frontend:

function SaveComponent({ attributes }) {
    const { title, showBorder } = attributes;
    const blockProps = useBlockProps.save({
        className: showBorder ? 'has-border' : '',
    });

    return (
        

{title}

); }

5. Adding Block Attributes

Define the data structure for your block:

attributes: {
    title: {
        type: 'string',
        default: '',
    },
    showBorder: {
        type: 'boolean',
        default: false,
    },
    content: {
        type: 'string',
        source: 'html',
        selector: '.block-content',
    },
}

6. Implementing Advanced Features

Add rich text editing and media upload capabilities:

import { RichText, MediaUpload, MediaUploadCheck } from '@wordpress/block-editor';
import { Button } from '@wordpress/components';

// In your Edit component
 setAttributes({ content: value })}
    placeholder={__('Enter your content...', 'my-plugin')}
/>


     setAttributes({ imageUrl: media.url })}
        allowedTypes={['image']}
        render={({ open }) => (
            
        )}
    />

7. Adding Custom Styles

Create CSS for your block:

.wp-block-my-plugin-custom-block {
    padding: 20px;
    margin: 20px 0;
}

.wp-block-my-plugin-custom-block.has-border {
    border: 2px solid #0073aa;
    border-radius: 8px;
}

.wp-block-my-plugin-custom-block h3 {
    margin-top: 0;
    color: #333;
}

8. Block Validation and Migration

Implement block validation to handle attribute changes:

deprecated: [
    {
        attributes: {
            // Old attribute structure
        },
        migrate(attributes) {
            return {
                // Convert to new structure
            };
        },
        save: OldSaveComponent,
    },
]

9. Testing Your Custom Block

Use WordPress’s built-in testing tools:

// Jest test example
import { render } from '@testing-library/react';
import EditComponent from './edit';

test('renders edit component', () => {
    const attributes = { title: 'Test Title' };
    const setAttributes = jest.fn();
    
    render();
    // Add assertions
});

10. Build and Deploy

Use WordPress scripts to build your block:

// package.json
{
  "scripts": {
    "build": "wp-scripts build",
    "start": "wp-scripts start"
  }
}

Best Practices:

  • Always use useBlockProps for proper block wrapper attributes
  • Implement proper internationalization with __() function
  • Test blocks in different themes and contexts
  • Follow WordPress coding standards
  • Use semantic HTML in your save functions

Key Takeaway: Custom WordPress blocks with React provide unlimited possibilities for content creation. Start with simple blocks and gradually add complexity as you master the WordPress block API.

Hashtags: #WordPress #GutenbergBlocks #React #WebDevelopment #CustomBlocks #WordPressDevelopment

Resources: