How to Build an Admin Page Using React in WordPress

Creating a custom admin page using React in WordPress can enhance the functionality and user experience of your site. In this guide, we’ll use @wordpress/element for React, and @wordpress/components for UI elements. We’ll also set up a minimal workable Webpack configuration.

Step 1: Install Necessary Packages

First, ensure you have Node.js and npm installed. Then, install the required packages:

npm install @wordpress/element @wordpress/components @babel/preset-react @babel/preset-env webpack webpack-cli webpack-dev-server babel-loader --save-dev

Step 2: Set Up Your Project Structure

Create the following directory structure:

my-plugin/
├── admin
   ├── build
      
   └── src
       └── index.js
├── package.json
├── webpack.config.js
└── wp-react.php

Step 3: Configure Webpack

Create webpack.config.js with the following configuration:

const path = require('path');

module.exports = {
    entry: './admin/src/index.js',
    output: {
        path: path.resolve(__dirname, 'admin/build'),
        filename: 'bundle.js'
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: ['@babel/preset-env', '@babel/preset-react']
                    }
                }
            }
        ]
    },
    devServer: {
        contentBase: path.join(__dirname, 'admin/build'),
        compress: true,
        port: 9000
    }
};

Step 4: Create React Component

In admin/src/index.js, create a simple React component:

import { render } from '@wordpress/element';
import { Button } from '@wordpress/components';

const App = () => (
    <div>
        <h1>My Admin Page</h1>
        <Button variant="primary" className="button default">Click Me</Button>
    </div>
);

render(<App />, document.getElementById('admin-page'));

Step 5: Set Up package.json

In your package.json, add scripts for building and watching your files:

{
  "name": "wp-react",
  "version": "1.0.0",
  "description": "",
  "main": "webpack.config.js",
  "scripts": {
    "build": "webpack --mode production",
    "watch": "webpack --mode development --watch"
  },
  "keywords": [],
  "author": "Kamal Hosen",
  "license": "GPL-v2-or-later",
  "devDependencies": {
    "@babel/preset-env": "^7.24.7",
    "@babel/preset-react": "^7.24.7",
    "@wordpress/components": "^28.2.0",
    "@wordpress/element": "^6.2.0",
    "babel-loader": "^8.3.0",
    "webpack": "^5.92.1",
    "webpack-cli": "^4.10.0",
    "webpack-dev-server": "^3.11.3"
  }
}

Step 6: Enqueue Your Scripts in WordPress

In my-plugin.php, enqueue the compiled JavaScript file:

<?php
/**
 * Plugin Name: WP React
 * Description: A simple plugin to demonstrate how to use React in WordPress.
 * Version: 1.0.0
 * Author: Kamal Hosen
 * Author URI: https://kamalhosen.com
 * License: GPL2
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain: wp-react
 * Domain Path: /languages
 * Requires at least: 5.2
 * Requires PHP: 7.2
 * 
 */

function wp_react_enqueue_scripts() {
    wp_enqueue_script(
        'wp-react-admin-page',
        plugins_url('admin/build/bundle.js', __FILE__),
        ['wp-element', 'wp-components'],
        filemtime(plugin_dir_path(__FILE__) . 'admin/build/bundle.js'),
        true
    );
}
add_action('admin_enqueue_scripts', 'wp_react_enqueue_scripts');

function wp_react_admin_page() {
    add_menu_page(
        'WP React Admin Page',
        'WP React',
        'manage_options',
        'wp-react',
        'wp_react_render_admin_page',
        '',
        6
    );
}
add_action('admin_menu', 'wp_react_admin_page');

function wp_react_render_admin_page() {
    echo '<div id="admin-page"></div>';
}
?>

Step 7: Build and Watch Your Project

Run the following commands to build and watch your project:

npm run build
npm run watch

Conclusion

By following these steps, you can set up a React-based admin page in WordPress, leveraging modern JavaScript development tools like Webpack and Babel. This setup ensures your code is modular, maintainable, and easy to extend. Happy coding!

Similar Posts

Leave a Reply

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