In this post I will demonstrate a way I was able to add external JS libraries to block plugin in WordPress.
For this example, I will be utilizing CanvasJS Javascript library to demonstration the implementation.
External JS Libraries In WordPress Block Plugin
Background
In CanvasJS, the Javascript needs to find an element via the ID tag. Example taken from their site below.
var chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
title: {
text: "Desktop Search Engine Market Share - 2016"
},
data: [{
type: "pie",
startAngle: 240,
yValueFormatString: "##0.00\"%\"",
indexLabel: "{label} {y}",
dataPoints: [
{y: 79.45, label: "Google"},
{y: 7.31, label: "Bing"},
{y: 7.06, label: "Baidu"},
{y: 4.91, label: "Yahoo"},
{y: 1.26, label: "Others"}
]
}]
});
chart.render();<div id="chartContainer" style="height: 370px; width: 100%;"></div>While building the WordPress block plugin, the return statement of the edit.js file will hold the elements that will be created in the DOM. React will not find the element when the code is placed in the logic of the plugin because the logic is run first.Β
So with the CanvasJS sample code above, this syntax will not work because the library will not be able to find the divΒ container that we want to add the chart to.
In React, there are a few items we will need to import to make this work.
Setup
I haven't incorporated any special attributes in this example. The focus in the post is being able to access and use external JS libraries. Updating the project with special attributes should be easy enough. For a quick reference, please review my past posts about these topics.
In the image shown below, add a place to store the Javascript library. I created a place to store it in the assets/scripts/ folder off the root of the custom block plugin.
Adding external JS libraries to block plugin will require editing a few files.
my-custom-blocks.php
To ensure the libraries are available on the frontend, you will need to add a reference to them in the block plugins PHP file at the root of the plugin.
At the bottom of this file, I added the following:
function r2creations24_my_custom_blocks_enqueue_script()
{
wp_enqueue_script( 'r2creations24_my_custom_blocks_script', plugin_dir_url( __FILE__ ) . 'assets/scripts/canvasjs.min.js' );
}
add_action('wp_enqueue_scripts', 'r2creations24_my_custom_blocks_enqueue_script');
Block.json
Based on a previous example linked above, no special attributes passed for extra data processing as of yet.
{
"$schema": "https://schemas.wp.org/trunk/block.json",
"apiVersion": 3,
"name": "r2creations24/my-custom-blocks-canvasjs",
"version": "0.1.0",
"title": "My Custom Blocks CanvasJS",
"category": "widgets",
"icon": "smiley",
"description": "Custom blocks created by R2creations24.",
"example": {},
"attributes": {
"bgColor": {
"type": "string",
"default": "#219b8b"
}
},
"supports": {
"html": false
},
"textdomain": "my-custom-blocks-canvasjs",
"editorScript": "file:./index.js",
"editorStyle": "file:./index.css",
"render": "file:./render.php",
"style": "file:./style-index.css",
"viewScript": "file:./view.js"
}
Style.Scss
This is used to style the DIV container that will hold the chart used in CanvasJS. This stylesheet will be used in both the editor as well as the frontend.
.wp-block-r2creations24-my-custom-blocks-canvasjs {
background-color: var(--bg-color);
color: #fff;
padding: 2px;
display: flex;
align-items: center;
}
#chart-container {
height: 370px;
width: 100%;
}Render.php
The frontend UI is implemented with the same sample coding given to use from the CanvasJS Javascript example usage. If you add in attributes, the updated attributes could be added to this file here with PHP. I have left in the old sample of retrieving a color attribute so you could see that implemented.
<?php
$bgColor = $attributes['bgColor'];
$style = "--bg-color: ".$bgColor.";";
?>
<p <?php echo get_block_wrapper_attributes(array("style" => $style)); ?>>
Hello from Render.PHP.....excited?!?
</p>
<div id="chart-container"></div>
<script>
var chart = new CanvasJS.Chart("chart-container", {
animationEnabled: true,
title: {
text: "Desktop Search Engine Market Share - 2016"
},
data: [{
type: "pie",
startAngle: 240,
yValueFormatString: "##0.00\"%\"",
indexLabel: "{label} {y}",
dataPoints: [
{y: 79.45, label: "Google"},
{y: 7.31, label: "Bing"},
{y: 7.06, label: "Baidu"},
{y: 4.91, label: "Yahoo"},
{y: 1.26, label: "Others"}
]
}]
});
chart.render();
</script>
Edit.js
Edit.js is where the fun part happens with adding external JS libraries to block plugins in WordPress.
We will need to import some functions to use as well as the external JS library itself.
import { useRef, useEffect } from '@wordpress/element';
import CanvasJS from '../../assets/scripts/canvasjs.min.js' const ref = useRef();
//use effect ensures the block of code fires after DOM is complete otherwise CanvasJS can't find element
useEffect(() => {
var chart = new CanvasJS.Chart(ref.current, {
animationEnabled: true,
title: {
text: "Desktop Search Engine Market Share - 2016"
},
data: [{
type: "pie",
startAngle: 240,
yValueFormatString: "##0.00\"%\"",
indexLabel: "{label} {y}",
dataPoints: [
{y: 79.45, label: "Google"},
{y: 7.31, label: "Bing"},
{y: 7.06, label: "Baidu"},
{y: 4.91, label: "Yahoo"},
{y: 1.26, label: "Others"}
]
}]
});
chart.render();
}, []);...
return (
...
<div ref={ref} id="chart-container">
...
);We will create a refΒ to the element we want to attach this library to as well as implement the logic of it in the useEffect to ensure it runs after DOM is loaded. The logic used is quite simply the same logic that CanvasJS uses in their example code shown above but instead of directly looking for the DIV with an ID, we pass along the ref.
Below is the complete code inside the edit.js file.
import { __ } from '@wordpress/i18n';
import {
useBlockProps,
PanelColorSettings,
InspectorControls
} from '@wordpress/block-editor';
import {
PanelBody
} from '@wordpress/components';
import './editor.scss';
import { useRef, useEffect } from '@wordpress/element';
import CanvasJS from '../../assets/scripts/canvasjs.min.js'
export default function Edit( { attributes, setAttributes } ) {
const newStyle = {
"--bg-color": attributes.bgColor
};
const blockProps = useBlockProps( { style: newStyle } );
function setBgColor(value){
if(value === undefined){
setAttributes({bgColor: "#219b8b"});
} else {
setAttributes({bgColor: value});
}
}
const ref = useRef();
//use effect ensures the block of code fires after DOM is complete otherwise CanvasJS can't find element
useEffect(() => {
var chart = new CanvasJS.Chart(ref.current, {
animationEnabled: true,
title: {
text: "Desktop Search Engine Market Share - 2016"
},
data: [{
type: "pie",
startAngle: 240,
yValueFormatString: "##0.00\"%\"",
indexLabel: "{label} {y}",
dataPoints: [
{y: 79.45, label: "Google"},
{y: 7.31, label: "Bing"},
{y: 7.06, label: "Baidu"},
{y: 4.91, label: "Yahoo"},
{y: 1.26, label: "Others"}
]
}]
});
chart.render();
}, []);
return (
<>
<InspectorControls>
<PanelBody title={ __( 'Settings', 'my-custom-blocks-canvasjs' ) }>
<PanelColorSettings
title = { __('Configure Color')}
colorSettings={
[
{
value: attributes.bgColor,
onChange: (value) => setBgColor(value),
label: __('Background Color')
}
]
}
/>
</PanelBody>
</InspectorControls>
<p { ...blockProps } >
{ __(
'This means nothing here, render.php changes static text.',
'my-custom-blocks-canvasjs'
) }
</p>
<div ref={ref} id="chart-container">
{ __(
'This means nothing here, render.php changes static text.',
'my-custom-blocks-canvasjs'
) }
</div>
</>
);
}
Hope this was useful.



