I was able to get React working in my custom Wordpress Plugin but I forgot how I got it working. What I'm trying to do is use a react component I have in NPM and use it as a Wordpress plugin.
I used npm to install my component from NPM.
my-custom-plugin.php:
function wp_enqueue_react() {
wp_enqueue_script('subreddit-posts',
plugin_dir_url( __FILE__ ) . 'js/node_modules/react-subreddit-posts/build/index.js',
['wp-element'],
'1.0',
false
);
wp_enqueue_script(
'wp-react-subreddit-posts',
plugin_dir_url(__FILE__) . 'js/index.js',
['wp-element'],
'1.0',
true
);
}
function subreddit_posts() {
return '<div id="subreddit"></div>';
}
add_shortcode('subreddit_posts', 'subreddit_posts');
add_action( 'wp_enqueue_scripts', 'wp_enqueue_react' );
my index.js which is pulled in:
const { createElement, render } = wp.element;
console.log('script is running');
wp.element.render(
wp.element.createElement(SubredditPosts, {
subreddit: "aww",
display: "gallery",
placeholder: "http://www.codeisdead.com/img/profile/Kyle.jpg",
width: "250px",
height: "300px"
},
null), document.getElementById('subreddit')
);
My console log shows. But I get this error:
Uncaught ReferenceError: module is not defined
Uncaught ReferenceError: SubredditPosts is not defined
module seems to be the react.production.min.js
file brought in by wp-element I believe.
Like I said I was able to get this working a few months ago but made some changes and broke something.
It seems logical to have the JS file with JSX to build with babel/webpack, but I don't remember having to use webpack or anything to build but I might be forgettin.
react-subreddit-posts/build/index.js
. And you've not loadedSubredditPosts
fromjs/index.js
?