Building a Reusable Gutenberg Block Library

Ashley Stanley | Frontend Developer

In an internal initiative at WebDevStudios, I was tasked with creating a set of reusable and flexible Gutenberg blocks. The goal was to streamline the development of future client projects by creating customizable blocks that could be easily adapted to various needs. This project aimed to solve common challenges faced by the team and offer long-term efficiency.

Project Overview

The goal of this project was to develop a series of flexible and reusable Gutenberg blocks. By focusing on key needs for client projects, I created a Slider block, a Testimonial block, and a Carousel block – each designed for maximum customization and ease of use. These blocks allow users to control various settings and embed dynamic content, which increases both efficiency and scalability in future client work.

Each of the three blocks I’m showcasing below will be accompanied by one code snippet each. These snippets come from different files required for building a Gutenberg block, highlighting various aspects of the development process. Each snippet will demonstrate unique parts of the block’s construction, so you can see how different files and components work together to create a fully functional, reusable Gutenberg block.

Challenges & Solutions

While building reusable Gutenberg blocks, there were key challenges that needed to be addressed. These challenges helped shape the overall architecture and functionality of the blocks, ensuring they would be useful in real-world client projects.

Challenges:

  • Flexibility vs. Simplicity:
    Creating blocks that were flexible enough to handle various types of content while still being intuitive and user-friendly.
  • Scalability:
    Ensuring the blocks could scale as new features and customization options were requested in the future.
  • Reusability:
    Developing blocks that could be reused in multiple client projects without extensive rework, saving time and effort.

Solutions:

  • By using JSON to store settings and preferences, I ensured that the blocks could be easily reused without complicating the backend process.
  • I used React to build dynamic block editors and leveraged custom PHP for server-side rendering, ensuring that the blocks were both responsive and easy to customize.
  • For customization, I focused on providing simple options for users to toggle settings like arrows, progress bars, and colors. I also designed the blocks to be modular so that they could easily integrate with other content on the page.

Slider Block

The Slider block allows users to create a dynamic slide experience by adding multiple Cover blocks inside the slider. Each Cover block acts as a slide, with its background image serving as both the slide’s background and its thumbnail in the slider’s navigation. The user can easily add content inside each slide (like text or images) using the Cover block editor.

Front End View

Custom Navigation Experience

Designed a fully customized navigation system to streamline user interaction, making it easier for users to explore different events and data on the platform.

Seamless Learning Experience

Integrated BuddyBoss and LearnDash to provide an immersive and interactive learning environment that adapts to the needs of users in the health simulation industry.

Exploring Charleston’s Hidden Gems

Created a user-friendly platform to help locals and visitors discover Charleston’s best-kept secrets through curated guides, event listings, and local business spotlights.

Back End View

Key Features:

  • Cover Block Integration: Users add Cover blocks within the Slider block. Each Cover block becomes a slide in the slider, and the background image of the Cover block becomes the thumbnail.
  • Progress Bar: A progress bar appears beneath each thumbnail, showing the progress of the current slide and giving users a visual cue of how much time is left before the next slide.
  • Thumbnails: The thumbnails at the bottom of the slider correspond to the background images of each Cover block. Clicking on a thumbnail navigates to the respective slide.

Code Snippet:

The following snippet from render.php demonstrates how the Slider block dynamically renders each slide (which is a Cover block). This snippet handles the rendering of navigation dots (which double as thumbnails) and ensures that the block correctly loops through the inner blocks to display each slide.

// Get inner blocks (Cover blocks used as slides)
$inner_blocks = $block->inner_blocks;

// Build wrapper attributes
$wrapper_classes = ['wp-block-wdsbt-wdsbt-slider-block'];
$wrapper_attributes = get_block_wrapper_attributes([
    'class' => implode(' ', $wrapper_classes)
]);

// Count the number of slides
$slide_count = !empty($inner_blocks) ? count($inner_blocks) : 0;
?>

<div <?php echo $wrapper_attributes; ?>>
    <div class="slider-container">
        <?php if (!empty($inner_blocks)): ?>
            <?php foreach ($inner_blocks as $index => $inner_block): ?>
                <div class="slider-slide" data-slide="<?php echo esc_attr($index); ?>">
                    <?php echo $inner_block->render(); ?>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>

    <?php if ($slide_count > 1): ?>
        <div class="slider-navigation">
            <div class="slider-dots">
                <?php for ($i = 0; $i < $slide_count; $i++): ?>
                    <button type="button"
                            data-slide="<?php echo esc_attr($index); ?>"
                            class="<?php echo $i === 0 ? 'active' : ''; ?>"
                            aria-label="<?php printf(esc_attr__('Go to slide %d', 'wdsbt-slider-block'), $i + 1); ?>">
                    </button>
                <?php endfor; ?>
            </div>
        </div>
    <?php endif; ?>
</div>

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus leo.

Testimonial Block

The Testimonial Block is a simple yet flexible block that allows clients to add an image, testimonial text, and details about the person providing the testimonial (name, position). It’s designed to be fully customizable while remaining easy to use.

By using InnerBlocks, I created a predefined layout that automatically loads essential elements such as testimonial text, name, headshot, and attribution. This layout allows users to easily add their own content without worrying about the structure or formatting. The block’s simple, intuitive setup ensures that clients can focus on the content they want to display while maintaining a clean and professional design.

This approach makes it easy for users to enter their testimonial content with minimal effort, offering both flexibility and consistency in the block’s design. The predefined layout simplifies the editing process and ensures that the final output looks polished and cohesive.

Front End View

This is where testimonial content can be added. You can edit any of this content the same as you would any paragraph content in WordPress.

Ashley Stanley

Frontend Developer

Back End View

Key Features:

  • Customizable Content with Predefined Layout: I created a predefined template for the Testimonial block, which automatically loads essential elements like testimonial text, name, headshot, and attribution. This layout is fully customizable in the block editor, allowing users to easily add or adjust content without having to worry about layout or design.
  • Flexible Content Types: The Testimonial block allows users to insert and customize a variety of content types. By including images, text, and groups, users can add a testimonial logo, testimonial content, and attribution details (like name and title), all of which can be arranged and styled as needed.
  • Easy to Use Block Structure: By using InnerBlocks, I made it simple for users to work within a predefined structure that allows for easy rearrangement of the block’s inner content. This flexibility empowers users to edit the content independently, while still keeping the layout organized and cohesive.
  • Predefined Layout for Attribution: I used a flex layout within a group block for the testimonial attribution section, which ensures that the headshot image and attribution text (name and title) are aligned properly. The layout provides a clean and professional appearance while allowing for future customizations in the design.
  • User-Friendly Placeholder Text: I added placeholder text to guide users when entering content, making it clear where to input the testimonial content, name, and title. This helps ensure a smooth experience for users who may not be familiar with Gutenberg or block-based editing.
  • Simplified Block Configuration: The Testimonial block comes pre-configured with class names and default styling, making it easy to implement the block within different themes. The design can be further customized with minimal effort by adjusting the class names and applying custom CSS.

Code Snippet:

The following snippet from edit.js demonstrates how I used the InnerBlocks component to automatically load a predefined block template into the Testimonial block. This template, which I built, is made up of various inner blocks (such as images, paragraphs, and groups) that users can customize directly in the block editor. The block also includes layout configurations and allows flexibility with the types of content that can be added.

import { useBlockProps, InnerBlocks } from '@wordpress/block-editor';
import './editor.scss';

const ALLOWED_BLOCKS = ['core/image', 'core/paragraph', 'core/group'];

const TEMPLATE = [
	['core/image', { className: 'testimonial-logo', align: 'left' }],
	['core/paragraph', { className: 'testimonial-content', placeholder: 'Enter testimonial content...' }],
	['core/group', { className: 'testimonial-attribution-wrapper', layout: { type: 'flex', justifyContent: 'flex-start' } }, [
		['core/image', { className: 'testimonial-headshot' }],
		['core/group', { className: 'testimonial-attribution-text' }, [
			['core/paragraph', { className: 'testimonial-attribution-name', placeholder: 'Enter name...' }],
			['core/paragraph', { className: 'testimonial-attribution-title', placeholder: 'Enter title...' }]
		]]
	]]
];

export default function Edit() {
	return (
		<div { ...useBlockProps() }>
			<InnerBlocks allowedBlocks={ ALLOWED_BLOCKS } template={ TEMPLATE } templateLock={ false } />
		</div>
	);
}

Carousel Block

The Carousel block allows you to create a dynamic, customizable carousel within your WordPress editor. This block enables users to add multiple slides, which can contain a variety of content types such as images, text, or groups. The carousel is fully customizable, offering settings for auto play, navigation dots, scrollbar, and navigation button styles, making it easy to tailor the block to fit your design needs. With its user-friendly interface, the Carousel block provides an engaging way to showcase content in a rotating, interactive format.

Front End View

Back End View

Key Features:

  • Dynamic Slide Content: The InnerBlocks component allows the carousel to accept and display dynamic content for each slide, making it flexible for various types of content (such as text, images, or groups).
  • Auto Play Functionality: The auto play feature can be activated to automatically advance the slides, and users can customize the auto play speed to control the time between slides.
  • Navigation Dots: The navigation dots provide an interactive way to navigate through the carousel. When enabled, these dots act as clickable thumbnails for each slide.
  • Customizable Button Style: The navigation button style can be customized to either a raised or outlined design, giving users control over the look and feel of the carousel’s navigation buttons.
  • Scrollbar Option: The optional scrollbar allows users to visually track their progress through the carousel. When enabled, it provides a clear indication of how far along the user is in the carousel.

Code Snippet:

The following snippet from edit.js demonstrates how I created the Carousel block that accepts other blocks as slides. The block includes customizable settings such as auto play, auto play speed, navigation dots, scrollbar, and navigation button style. These settings allow users to fully customize the carousel’s behavior and appearance in the block editor.

// Ensure we have the required variables
if (!isset($block) || !isset($attributes)) {
    return '<div>Block or attributes not set</div>';
}

// Get inner blocks (slides)
$inner_blocks = $block->inner_blocks;
$slide_count = count($inner_blocks);

// Build wrapper attributes
$wrapper_classes = ['wp-block-wdsbt-wdsbt-slider-block'];
$wrapper_attributes = get_block_wrapper_attributes(['class' => implode(' ', $wrapper_classes)]);

?>

<div <?php echo $wrapper_attributes; ?>>
    <div class="slider-container">
        <?php foreach ($inner_blocks as $index => $inner_block): ?>
            <div class="slider-slide" data-slide="<?php echo esc_attr($index); ?>">
                <?php echo $inner_block->render(); ?>
            </div>
        <?php endforeach; ?>
    </div>

    <?php if ($slide_count > 1): ?>
        <div class="slider-navigation">
            <div class="slider-dots">
                <?php for ($i = 0; $i < $slide_count; $i++): ?>
                    <button type="button" data-slide="<?php echo esc_attr($index); ?>" class="<?php echo $i === 0 ? 'active' : ''; ?>" aria-label="Go to slide <?php echo $i + 1; ?>"></button>
                <?php endfor; ?>
            </div>
        </div>
    <?php endif; ?>
</div>