Using React.js with WordPress

Posted on Saturday, July 15th, 2017

In this post I’ll show you how you can write ES6, Webpack with React.js and use it in WordPress.

The process will use Gulp to compile a folder /src/js in your WordPress theme into a bundle.js that will then be wp_enqueue in your functions.php. You can check out the whole project at github.

1. Create a folder ~src/js~ in your theme.


theme
|- src
|-- src/js/index.js
|- index.php
|- style.css
|- functions.php

Put this into your gulpfile.js


gulp.task("build", function(){
return browserify({
entries: ["./src/js/index.js"],
extensions: [".js", ".jsx"]
})
.transform(babelify.configure({
presets : ["es2015", "react"]
}))
.bundle()
.pipe(source("bundle.js"))
.pipe(gulp.dest("./build"))
;
});

In the index.js, write your React components.


import React, { Component } from 'react';
import ReactDOM from "react-dom";

class App extends Component {
constructor() {
super();
this.state = {
loading: true
};
}
componentDidMount() {
this.fetchData();
}
render() { }
}