Get 50% Discount Offer 26 Days

Recommended Services
Supported Scripts
WordPress
Hubspot
Joomla
Drupal
Wix
Shopify
Magento
Typeo3
WordPress Plugin Development with React, Vue, and Tailwind

The WordPress ecosystem has evolved to embrace modern JavaScript frameworks and CSS tools, enabling developers to build dynamic admin interfaces and Gutenberg blocks with the same tools used in standalone applications. Whether you’re creating a complex Gutenberg block with React, a Vue-powered admin dashboard, or a Tailwind-styled plugin, integrating these frameworks requires careful setup to ensure compatibility and performance.

This guide provides sequential instructions for WordPress Plugin Development and merging React, Vue and Tailwind CSS into WordPress plugins. It also includes instructions for Gutenberg blocks administration pages and style guidelines.

Why Use Modern Frameworks For WordPress Plugin Development?

  1. Enhanced User Experience: Reactive interfaces improve usability.
  2. Code Maintainability: Component-based architectures simplify scaling.
  3. Performance: Modern tools optimize asset loading and rendering.
  4. Developer Familiarity: Leverage existing knowledge of React/Vue.
Why Use Modern Frameworks in WordPress

1. Integrating React into Gutenberg Blocks

WordPress block editor (Gutenberg) is built with React, making it the natural choice for custom blocks.

Step 1: Set Up the Development Environment

Use the official @wordpress/create-block package to scaffold a block:

// Bash Code

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

This code generates a block with the following:

  • A React component in src/index.js.
  • Webpack configuration for compiling JS/SCSS.
  • Automatic asset enqueuing via block.json.

Step 2: Build a Custom Block

Edit src/edit.js to create a dynamic block:

// jsx Code

import { useBlockProps } from '@wordpress/block-editor';  

import { TextControl } from '@wordpress/components';  

export default function Edit({ attributes, setAttributes }) {  

    return (  

        <div {...useBlockProps()}>  

            <TextControl  

                label="Enter Text"  

                value={attributes.text}  

                onChange={(text) => setAttributes({ text })}  

            />  

        </div>  

    );  

}

Step 3: Enqueue Assets

WordPress automatically enqueues JS/CSS defined in block.json:

// json Code

{  

    "name": "my-custom-block",  

    "editorScript": "file:./build/index.js",  

    "editorStyle": "file:./build/index.css",  

}

Key Dependencies:

  • @wordpress/blocks: Register blocks.
  • @wordpress/components: Use pre-built UI elements.
  • `@wordpress/scripts**: Compile code (Babel, Webpack).

Build Command:

// Bash Code

npm run build

2. Using Vue.js in Admin Pages

For admin interfaces outside Gutenberg, Vue.js offers a lightweight alternative.

Step 1: Set Up a Vue Project

Initialize a Vue app with Vite:

// Bash Code

npm create vue@latest my-admin-app

Configure vite.config.js to build on the WordPress plugins directory:

// Js Code

export default {  

    build: {  

        outDir: '../wp-content/plugins/my-plugin/admin',  

        emptyOutDir: true,  

    }  

};

Step 2: Create a Vue Component

Build a dashboard component in src/App.vue:

// Vue Code

<template>  
    <div id="my-vue-app">  
        <h1>{{ title }}</h1>  
        <button @click="fetchData">Load Data</button>  
        <ul>  
            <li v-for="item in items" :key="item.id">{{ item.name }}</li>  
        </ul>  
    </div>  
</template>  

<script>  
export default {  
    data() {  
        return {  
            title: 'Vue Admin Dashboard',  
            items: []  
        };  
    },  
    methods: {  
        async fetchData() {  
            const response = await fetch('/wp-json/my-plugin/v1/data');  
            this.items = await response.json();  
        }  
    }  
};  
</script>  

Step 3: Enqueue Vue Assets in WordPress

In your plugin PHP file, enqueue the compiled assets:

// PHP Code

add_action('admin_enqueue_scripts', 'enqueue_vue_app');  

function enqueue_vue_app($hook) {  

    if ($hook !== 'toplevel_page_my-plugin') {  

        return;  

    }  

    wp_enqueue_script(  

        'my-vue-app',  

        plugins_url('admin/assets/index.js', __FILE__),  

        array(), // No dependencies (Vue is bundled)  

        filemtime(plugin_dir_path(__FILE__) . 'admin/assets/index.js')  

    );  

    wp_enqueue_style(  

        'my-vue-app-style',  

        plugins_url('admin/assets/style.css', __FILE__)  

    );  

}

Step 4: Mount Vue to the Admin Page

Add a container to your admin page template:

// PHP Code

function render_admin_page() {  

    echo '<div id="my-vue-app"></div>';  

} 

Note: For better integration, use wp_localize_script() to pass data from PHP to Vue:

// PHP Code

wp_localize_script('my-vue-app', 'wpData', [  

    'nonce' => wp_create_nonce('wp_rest'),  

    'apiUrl' => rest_url('my-plugin/v1/data')  

]);

3. Adding Tailwind CSS to a Plugin

Tailwind CSS simplifies styling without writing custom CSS.

Step 1: Install Tailwind

Initialize Tailwind in your plugin directory:

// Bash Code

npm install -D tailwindcss postcss autoprefixer  

npx tailwindcss init -p

Step 2: Configure tailwind.config.js

Purge unused styles to reduce file size:

// Js Code

module.exports = {  

    content: [  

        './admin/**/*.php',  

        './blocks/**/*.js',  

    ],  

    theme: {  

        extend: {},  

    },  

    plugins: [],  

}

Step 3: Create a Tailwind Stylesheet

Add src/input.css:

// CSS Code

@tailwind base;  

@tailwind components;  

@tailwind utilities;

Step 4: Compile CSS

Update package.json to build Tailwind:

// JSON Code

"scripts": {  

    "build:css": "tailwindcss -i src/input.css -o build/tailwind.css --minify"  

} 
// Bash Code

npm run build:css

Step 5: Enqueue Tailwind in WordPress

Load the compiled CSS only where needed:

// PHP Code

add_action('admin_enqueue_scripts', 'enqueue_tailwind');  

function enqueue_tailwind($hook) {  

    if ($hook === 'toplevel_page_my-plugin') {  

        wp_enqueue_style(  

            'my-tailwind',  

            plugins_url('build/tailwind.css', __FILE__)  

        );  

    }  

}

Best Practices

  • Dependency Management:
    • Use wp-element as a dependency for React components to avoid bundling duplicate libraries.
// PHP Code

wp_enqueue_script('my-react-app', $js_path, array('wp-element'), $version);
  • Code Splitting:
    • Split Vue/React code into chunks using dynamic imports:
// JS Code

const SettingsPage = () => import('./SettingsPage.vue');
  • Security:
    • Verify nonces in REST API endpoints:
// PHP Code

register_rest_route('my-plugin/v1', '/data', array(  

    'methods' => 'GET',  

    'callback' => function ($request) {  

        if (!wp_verify_nonce($request->get_header('X-WP-Nonce'), 'wp_rest')) {  

            return new WP_Error('forbidden', 'Unauthorized', array('status' => 403));  

        }  

        // Return data  

    },  

));
  • Performance:
    • Use lazy loading for non-critical components.
    • Cache compiled assets using filemtime() for versioning.

Troubleshooting Common Issues

  • React/Vue Not Rendering:
    • Ensure the DOM container exists before initializing the app.
    • Check in the browser console for JavaScript errors.
  • Dependency Conflicts:
    • Use wp.dependencies to check registered scripts:
// Bash Code

wp script list
  • Tailwind Styles Missing:
    • Verify the content paths in tailwind.config.js.
    • Rebuild CSS after markup changes.
  • CORS Errors in REST API:
    • Pass the X-WP-Nonce header in API requests:
fetch('/wp-json/my-plugin/v1/data', {  

    headers: {  

        'X-WP-Nonce': wpData.nonce  

    }  

});

Real-World Example: Analytics Dashboard Plugin

Tech Stack:

  • Gutenberg Block (React): Displays real-time stats in the editor.
  • Admin Page (Vue): Interactive charts for data visualization.
  • Styling (Tailwind): Consistent UI across the plugin.

Workflow:

  • Users configure settings via a React block.
  • Data is fetched via the REST API and displayed in Vue charts.
  • Tailwind ensures a cohesive design without conflicting with admin CSS styles.

Implementation Steps:

  • Gutenberg Block: Create a block that allows users to select data ranges and display stats.
  • Vue Admin Page: Use Vue to create a dashboard that fetches and visualizes data based on user input from the block.
  • Tailwind CSS: Use Tailwind to style both the block and the admin page to ensure a modern look and feel.

Frequently Asked Questions

Yes! While React is natively supported in Gutenberg, you can use it in admin pages by enqueuing React and ReactDOM from WordPress core. Use wp_enqueue_script() with the wp-element dependency (WordPress’s React wrapper) and mount your app to a DOM container.

To prevent conflicts, bundle Vue.js locally with your plugin instead of relying on a CDN. Use npm install vue and compile it into your JavaScript bundle. This ensures your plugin uses a specific Vue version isolated from other scripts.

Tailwind purges unused CSS by default. Ensure your tailwind.config.js includes all template paths where Tailwind classes are used. For example:

// Js Code

content: [  
    './admin/**/*.php',  
    './blocks/**/*.js',  
]

Rebuild your CSS after updating the config.

Always validate nonces and permissions in REST API endpoints. Pass a nonce via wp_localize_script() and include it in API request headers:

// PHP Code

wp_localize_script('my-vue-app', 'wpData', [  
    'nonce' => wp_create_nonce('wp_rest'),  
]);
// Js Code

fetch('/wp-json/my-plugin/v1/data', {  
    headers: { 'X-WP-Nonce': wpData.nonce }  
}); 

Yes, but it’s not recommended due to increased bundle size and potential conflicts. If necessary, isolate frameworks to different admin pages or blocks. For example, use React for Gutenberg blocks and Vue for standalone admin interfaces.

Conclusion

Integrating modern CSS and JavaScript frameworks like React, Vue, and Tailwind into WordPress plugins opens up a world of possibilities for developers. These tools allow you to create dynamic, responsive, and user-friendly interfaces that improve the experience for users and administrators alike.

This guide has provided a complete overview of how to set up and integrate these frameworks into your WordPress plugins, covering everything from initial setup to best practices and troubleshooting. By following these steps, you can ensure that your plugins not only meet the functional requirements but also provide a polished and modern user experience.

As you embark on your journey to integrate these frameworks, remember to keep performance, security, and maintainability in mind. With the right approach, you can harness the power of modern web technologies to elevate your WordPress development projects. Happy coding!

About the writer

Hassan Tahir Author

Hassan Tahir wrote this article, drawing on his experience to clarify WordPress concepts and enhance developer understanding. Through his work, he aims to help both beginners and professionals refine their skills and tackle WordPress projects with greater confidence.

Leave a Reply

Your email address will not be published. Required fields are marked *

Lifetime Solutions:

VPS SSD

Lifetime Hosting

Lifetime Dedicated Servers