Tag: React

  • How to Build Your First Custom Gutenberg Block

    The WordPress editor has evolved significantly, shifting from a simple text field to a powerful, block-based design system. If you are a developer looking to move beyond third-party page builders, learning how to build a custom Gutenberg block is your next logical step to gaining full control over your site’s architecture.

    The Prerequisites for Block Development

    Before diving into the code, you need a local development environment. I recommend using LocalWP or Docker to spin up a WordPress installation quickly. You will also need to have Node.js and npm installed on your machine, as the modern block development process relies heavily on JavaScript build tools.

    The Toolchain: @wordpress/create-block

    The official WordPress team provides a command-line tool that handles the complex configuration for you. Instead of setting up Webpack from scratch, use the scaffolding tool:

    npx @wordpress/create-block my-first-block

    This command generates a complete plugin structure, including the necessary build scripts, block metadata, and boilerplate code.

    Understanding the Block Structure

    Once your block is generated, take a look at the file directory. The two most important files are block.json and edit.js.

    • block.json: This is the heart of your block. It stores metadata like the block name, title, category, and supported features.
    • edit.js: This defines the React component for the editor interface. This is what the user interacts with in the backend.
    • save.js: This file defines how the block’s content is serialized and saved into the WordPress database as HTML.

    Building Your First UI

    To render content, you will work primarily in edit.js. Gutenberg uses React, so you can leverage built-in components like RichText or InspectorControls to make your block interactive.

    import { useBlockProps, RichText } from '@wordpress/block-editor';
    
    export default function Edit({ attributes, setAttributes }) {
        return (
            <div {...useBlockProps()}>
                <RichText
                    tagName="p"
                    value={attributes.content}
                    onChange={(val) => setAttributes({ content: val })}
                    placeholder="Enter your custom text here..."
                />
            </div>
        );
    }

    Handling Attributes

    Attributes allow your block to store data. You must define these in your block.json file to ensure WordPress knows how to read and write the data correctly. For example, if you want a custom color or text input, define them as schema objects within the JSON file.

    Compilation and Deployment

    Since modern block code is written in JSX/ESNext, browsers cannot read it directly. You need to compile your code into plain JavaScript that the browser understands. In your plugin folder, run the following command:

    npm run build

    This generates the final build/ directory. Once the build process finishes, activate your plugin in the WordPress dashboard, and your custom block will appear in the editor under the category you assigned.

    Best Practices for Future-Proof Blocks

    • Always use block.json: It allows WordPress to register your block server-side, which improves performance.
    • Keep React code clean: Decompose your components into smaller files if your block logic starts to grow complex.
    • CSS is key: Use editor.scss for backend styles and style.scss for frontend display to ensure a consistent experience.

    Building your own Gutenberg blocks is the most rewarding way to customize WordPress. Start simple, experiment with the @wordpress/components library, and you will soon be creating highly dynamic, reusable UI elements that feel like a native part of the WordPress ecosystem.

  • How to Build Your First Custom Gutenberg Block

    The WordPress block editor, Gutenberg, has revolutionized how we build content, but the real power lies in creating your own custom blocks. If you have ever wanted to break free from the constraints of pre-built page builders and craft bespoke experiences for your users, you are in the right place.

    The Modern Workflow: Using Create Block

    Gone are the days of manual webpack and babel configuration. The official @wordpress/create-block tool is the scaffolding standard for developers. It sets up your project structure, build scripts, and local development environment in seconds.

    Getting Started

    Ensure you have Node.js installed on your machine. Open your terminal, navigate to your plugin directory, and run the following command:

    npx @wordpress/create-block my-custom-block

    This command generates a complete plugin folder containing everything you need, including the block registration logic, the editor-side JS, and the frontend rendering.

    Understanding the Block Structure

    Once generated, you will notice three key files that form the heart of your block:

    • block.json: The metadata file that defines the block’s name, attributes, and supported features.
    • edit.js: Contains the component code that handles the block’s interface within the WordPress editor.
    • save.js: Defines how the block’s data is serialized and rendered on the frontend.

    Working with block.json

    The block.json file is the most important component. It uses a declarative syntax to tell WordPress exactly how your block behaves. Here is a snippet of what a standard configuration looks like:

    { "name": "create-block/my-custom-block", "title": "My Custom Block", "category": "widgets", "attributes": { "content": { "type": "string", "default": "Hello World" } } }

    Defining Attributes and Editing

    Attributes allow your block to store data dynamically. If you want a user to be able to type custom text into your block, you must map that data to an attribute. In your edit.js file, you will use the useBlockProps and RichText components from the @wordpress/block-editor package.

    By binding an attribute to a RichText input, you create a seamless connection between the user’s input in the editor and the final output rendered on the page.

    The Build Process and Deployment

    Because Gutenberg blocks rely on React and JSX, your code needs to be transpiled into browser-readable JavaScript. While you are working, keep your development server running in a separate terminal window:

    npm start

    This will watch your files for changes and automatically rebuild your assets. When you are ready for production, simply run npm run build to generate optimized, minified files that are ready for your live WordPress environment.

    Practical Tips for Success

    • Stay Modular: Keep your styling in style.scss and editor-specific styling in editor.scss to avoid polluting the public frontend.
    • Leverage Components: Don’t reinvent the wheel. Use the official @wordpress/components library for buttons, toolbars, and inputs.
    • Validate: Always test your block with the Block Validator in the editor to ensure your save() function matches the HTML in the content.

    Building your first block is a rite of passage for every WordPress developer. By mastering the core API, you unlock the ability to turn static designs into interactive, reusable content modules that elevate any project. Start small, experiment with attributes, and embrace the power of modern WordPress development.

  • How to Build Your First Custom Gutenberg Block

    The WordPress block editor, Gutenberg, has revolutionized how we build websites, moving away from rigid page templates toward a flexible, block-based architecture. For developers, mastering the creation of custom blocks is the single most effective way to provide clients with a tailored content experience.

    Understanding the Gutenberg Ecosystem

    Before writing code, it is essential to understand that Gutenberg blocks are fundamentally JavaScript applications. While WordPress handles the PHP registration on the server side, the block’s rendering, editor interface, and attributes are managed by React. To build modern blocks, you need a basic grasp of:

    • React & JSX: The core library for component rendering.
    • Node.js & npm: Required for building and compiling your block assets.
    • @wordpress/create-block: The official scaffolding tool that handles the complex build configuration for you.

    Step 1: Scaffolding Your Block

    Instead of manually configuring Webpack or Babel, use the official WordPress scaffolding tool. Open your terminal in your wp-content/plugins directory and run the following command:

    npx @wordpress/create-block my-first-block

    This command generates a complete plugin directory with all necessary files, including the block.json file, which acts as the metadata registry for your block.

    Step 2: Defining Block Metadata

    The block.json file is the heart of your creation. It tells WordPress what your block is named, where its assets are located, and what attributes it supports. Here is a simplified example of what that looks like:

    { "name": "create-block/my-first-block", "title": "My Custom Block", "editorScript": "file:./index.js", "style": "file:./style.css" }

    Setting Up Attributes

    Attributes are your block’s data. If you want your block to store text or color data, you define them inside block.json. This allows WordPress to save the block state into the database using HTML comments.

    Step 3: Developing the Edit and Save Functions

    Every block has two main functions: edit and save. The edit function determines how your block behaves inside the Gutenberg editor, while the save function determines what is rendered on the front end.

    The Edit Function

    This is where you build the UI components using WordPress components like RichText or InspectorControls. Since Gutenberg is built on React, you will use hooks like useBlockProps to ensure your block plays nicely with the editor’s styling.

    export default function Edit( { attributes, setAttributes } ) { return ( <p { ...useBlockProps() }> Hello World! </p> ); }

    The Save Function

    The save function returns the static markup that will be saved to the database. Keep this simple to ensure performance remains high.

    Essential Tips for Success

    • Use the Block Editor Handbook: It is the definitive source of truth for all WordPress block development.
    • Build for Reusability: Always try to make your attributes dynamic so the block remains useful in various design contexts.
    • Test for Accessibility: Ensure your block produces clean HTML5 tags, not just generic <div> elements.

    Conclusion

    Building your first Gutenberg block is an exciting milestone that opens the door to creating bespoke, high-performance WordPress experiences. By leveraging the @wordpress/create-block tool and embracing the React-based architecture, you can move beyond simple plugins and start building the future of the web. Start small, experiment with attributes, and your proficiency will grow with every iteration.