WordPress React.
You can skip this part: It’s an evening and I’m writing this article. Next two days are my weekend. So, definitely I’ll go to sleep very late. Anyway, 2 days ago I’ve learnt how to use React in WordPress admin menu page and I want to keep it as a document here. So, surely you can read and write your comment :). Let’s get started……
Prerequisite:
- WordPress Development Site
- Node/NPM Development Tools
- Code Editor
wordpress React
Step 1: Open terminal/command line on your plugin root directory and write the below command and enter
npm install @wordpress/scripts --save-dev
Step 2: Add the below json in the package.json file (make sure you’ve added this properly according to json syntax)
"scripts": {
"build": "wp-scripts build",
"check-engines": "wp-scripts check-engines",
"check-licenses": "wp-scripts check-licenses",
"format": "wp-scripts format",
"lint:css": "wp-scripts lint-style",
"lint:js": "wp-scripts lint-js",
"lint:md:docs": "wp-scripts lint-md-docs",
"lint:pkg-json": "wp-scripts lint-pkg-json",
"packages-update": "wp-scripts packages-update",
"plugin-zip": "wp-scripts plugin-zip",
"start": "wp-scripts start",
"test:e2e": "wp-scripts test-e2e",
"test:unit": "wp-scripts test-unit-js"
}
Step 3: Create a directory and file called “src/index.js” on the plugin root.
Step 4: Run the below command
npm start
After run this command you’ll see a new directory called build.
Step 5: Add the below code in the src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
const container = document.getElementById('render-root');
const root = ReactDOM.createRoot(container);
root.render(<h1>Hello From React!</h1>);
Step 6: Add the below code in your plugin main file. It’ll register a menu page and enqueue the react built script;
function your_plugin_menu() {
add_menu_page(
'Your Plugin Settings', // Page title
'Your Plugin', // Menu title
'manage_options', // Capability required
'your-plugin-settings', // Menu slug
'your_plugin_page' // Callback function
);
}
function your_plugin_page() {
//include the index.assest.php file for taking the dependencies and version
$mfile = include(plugin_dir_path(__FILE__) . 'build/index.asset.php');
//enqueue the react built script
wp_enqueue_script('your-scripts', plugin_dir_url(__FILE__) . 'build/index.js', $mfile['dependencies'], $mfile['version'], true);
//make sure the id name is same as we render the react code
echo '<div id="render-root"></div>';
}
add_action('admin_menu', 'your_plugin_menu');
Step 7: Navigate your menu page and see the output

Congratulations! It’s done!
If you face any difficulty feel free to comment.
Thank you!

Leave a Reply