When it comes to building a dynamic admin page, harnessing the power of a framework is a smart choice. In the WordPress ecosystem, React is the preferred choice. In this article, I’ll show you how to seamlessly integrate React with the @wordpress/scripts
package, unlocking the potential for creating dynamic and responsive admin pages.
"dependencies": {
"@wordpress/scripts": "*"
}
1. Install the package
Code structuring methods can vary significantly among developers, and in my case, I prefer to follow this particular structure.
assets
--build
--index.asset.php
--index.js
--index02.asset.php
--index02.js
--src
--js
---index.js
---index02.js
--scss
---index.scss
---index02.scss
--package.json
To install the package, simply execute the following command:
npm i @wordpress/scripts
For additional information, I recommend referring to the official documentation.
2. Add package.json scripts
To generate multiple scripts, it’s essential to include the parent folder in the script path within the package.json
file. Here’s an illustrative example:
{
...
"scripts": {
"start": "wp-scripts start src/js/*.js",
"build": "wp-scripts build src/js/*.js"
}
...
}
3. Enqueue your scripts
To enqueue your styles and scripts, the @wordpress/scripts
package proves invaluable in generating a version that automatically updates each time you make changes to your files. Additionally, it efficiently manages script dependencies, simplifying the entire process.
$index_assets = 'your_path/assets/build/index.asset.php';
wp_enqueue_style( 'index-style', 'your_path/assets/build/index.css', array(), $index_assets['version'], 'all' );
wp_enqueue_script( 'ml-single-inventaire', 'your_path/assets/build/index.js', $index_assets['dependencies'], $index_assets['version'], true );
4. Import React
The @wordpress/scripts
package conveniently includes all the essential React functions within its components. This eliminates the need to separately install React. To illustrate, here’s an example.
import {render, useState} from "@wordpress/element";
const Page = () => {
const [items, setItems] = useState([]);
return (
<div>
...
</div>
);
};
render( <Page/>, document.querySelector('#JS-page') );