Using React.js with WordPress

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.
[code]
theme
|- src
|– src/js/index.js
|- index.php
|- style.css
|- functions.php
[/code]

Put this into your gulpfile.js

[code]
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”))
;
});
[/code]

In the index.js, write your React components.

https://gist.github.com/pmqa/16df7be6ccecfa93b6a85ce7ce60ea82

[code]
import React, { Component } from ‘react’;
import ReactDOM from “react-dom”;

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