React Apps on WordPress REST API Tutorial

7 minutes read

React APP WordPress REST API

WordPress is no doubt a popular and equally powerful CMS but, it is lots of HTML and PHP loops that are quite often very hard to comprehend hence, developing on top of WordPress seems very frustrating. Let us now explore possibilities of ReactJS for development of app front end, React Router for routing and Webpack for keeping it all together. You can also integrate Advanced Custom Fields for creation of a very intuitive solution.

 

Project Setup
Suppose name of project “wp-api”. What you need do next is t include it in package.json and run npm install:

{
“name”: “wp-api”,
“version”: “1.0.0”,
“description”: “”,
“main”: “index.js”,
“dependencies”: {
“alt”: “^0.18.6”,
“axios”: “^0.15.3”,
“lodash”: “^4.17.4”,
“react”: “^15.4.2”,
“react-dom”: “^15.4.2”,
“react-router”: “^3.0.1”
},
“devDependencies”: {
“babel-core”: “^6.21.0”,
“babel-loader”: “^6.2.10”,
“babel-preset-es2015”: “^6.18.0”,
“babel-preset-react”: “^6.16.0”,
“react-hot-loader”: “^1.3.1”,
“webpack”: “^1.14.0”,
“webpack-dev-server”: “^1.16.2”
},
“scripts”: {
“test”: “echo \”Error: no test specified\” && exit 1″
},
“author”: “”,
“license”: “ISC”

Install webpack and webpack-dev-server globally even if this was not done beforehand,

npm i webpack webpack-dev-server -g

Create index.html and webpack.config.js in the project folder. The index.html file will include piece of code as mentioned below:

 <!DOCTYPE html>

<html>
<head>
<title>WP API</title>
</head>
<body>
<div id=”app”></div> <!– This div will be holding the app –>
<script src=”bundle.js”></script> <!– This is the main JS file that gets bundled by webpack –>
</body>
</html>
(BI)

Coming back to webpack.config.js, a file that builds the project apart from listening for live updates. Paste following in webpack.config.js:

(BI)
var webpack = require(‘webpack’);
var path = require(‘path’);

module.exports = {
devtool: ‘inline-source-map’, // This will show line numbers where errors are accured in the terminal
devServer: {
historyApiFallback: true, // This will make the server understand “/some-link” routs instead of “/#/some-link”
},
entry: [
‘webpack-dev-server/client?http://127.0.0.1:8080/’, // Specify the local server port
‘webpack/hot/only-dev-server’, // Enable hot reloading
‘./src/index’ // This is where Webpack will be looking for the entry index.js file
],
output: {
path: path.join(__dirname, ‘public’), // This is used to specify folder for producion bundle. Will not be used here, but it’s a good practice to have it
filename: ‘bundle.js’ // Filename for production bundle
},
resolve: {
modulesDirectories: [‘node_modules’, ‘src’], // Folders where Webpack is going to look for files to bundle together
extensions: [”, ‘.js’] // Extensions that Webpack is going to expect
},
module: {
// Loaders allow you to preprocess files as you require() or “load” them. Loaders are kind of like “tasks” in other build tools, and provide a powerful way to handle frontend build steps.
loaders: [
{
test: /\.jsx?$/, // Here we’re going to use JS for react components but including JSX in case this extension is prefered
exclude: /node_modules/, // Speaks for itself
loaders: [‘react-hot’, ‘babel?presets[]=react,presets[]=es2015’] // Modules that help with hot reloading and ES6 transcription
}
]
},
plugins: [
new webpack.HotModuleReplacementPlugin(), // Hot reloading
new webpack.NoErrorsPlugin() // Webpack will let you know if there are any errors
]
}

 It is recommended to add a some more folders to the project. Create a folder named “src” and a folder “components” and index.js further inside it are to be created.

Thus the folder structure will look as below:
wp-api/
 — node_modules/
 — src/
 — — components/
 — — index.js
 — index.html
 — package.json
 — webpack.config.js
index.js is the very entry point for Webpack that will also all routes for project.

 

Dynamic Routes

Currently only index routes are set in the application. This will limit your chance to bring pages created at WordPress backend to the front end. we need to create a method in index.js to dynamically add routes to React Router. Let this method be buildRoutes():

import React from ‘react’;
import {render} from ‘react-dom’;
import App from ‘./components/App.js’;
import Home from ‘./components/Home.js’;

import {
browserHistory,
IndexRoute,
Redirect,
Route,
Router
} from ‘react-router’;

import DataActions from ‘./actions/DataActions.js’;

class AppInitializer {

buildRoutes(data) {
return data.pages.map((page, i) => {
return (
<Route
component={ Home }
key={ page.id }
path={`/${page.slug}`}
/>
);
});
}

run() {
DataActions.getPages((response)=>{
render(
<Router history={browserHistory}>
<Route path=”/” component={ App } >
<IndexRoute component={ Home } />

{this.buildRoutes(response)}
</Route>
<Redirect from=”*” to=”/” />
</Router>

, document.getElementById(‘app’)
);
});
}
}

new AppInitializer().run();

This method loops within all pages returned by the WordPress API and returns new routes. It also add “Home ” element with every route.

 

Page Templates

We can use page elements by letting React know which template to use with a particular page. Page slug returned by the API can be used to map templates for different routes. If two pages with slugs “home” and “about” are present and we need to create a file that will map page slug to React component paths. We can assume name of file.
views.js and put it in “components” folder:

export default {
‘home’: ‘./components/Home.js’,
‘about’: ‘./components/About.js’
};

Similarly About.js should be created to map the “about” slug.

To update in index.js file we will make it request the right component dynamically.

 

import React from ‘react’;
import {render} from ‘react-dom’;
import App from ‘./components/App.js’;
import Home from ‘./components/Home.js’;
import views from ‘./components/views.js’;

import {
browserHistory,
IndexRoute,
Redirect,
Route,
Router
} from ‘react-router’;

import DataActions from ‘./actions/DataActions.js’;

class AppInitializer {

buildRoutes(data) {
return data.pages.map((page, i) => {
const component = views[page.slug];
return (
<Route
getComponent={(nextState, cb) => {
require.ensure([], (require) => {
cb(null, require(component).default);
});
}}
key={ page.id }
path={`/${page.slug}`}
/>
);
});
}

run() {
DataActions.getPages((response)=>{
render(
<Router history={browserHistory}>
<Route path=”/” component={ App } >
<IndexRoute component={ Home } />

{this.buildRoutes(response)}
</Route>
<Redirect from=”*” to=”/” />
</Router>

, document.getElementById(‘app’)
);
});
}
}

new AppInitializer().run();

 

views.js is included in the file and updates have been done to the buildRoutes() method to require the right component.
To gather page-specific data just call the DataStore.getPageBySlug(slug) method and provide the current page slug:

render() {
let page = DataStore.getPageBySlug(‘about’);
return (
<div>
<h1>{page.title.rendered}</h1>
</div>
);
}

Dynamic Navigation
In order to reflect all WordPress backend page links we will add a global navigation. Start with creation of Nav.sj component inside “components” folder:

import React from ‘react’;
import { Link } from ‘react-router’;
import _ from ‘lodash’;

import DataStore from ‘./../stores/DataStore.js’;

class Nav extends React.Component {
render() {
let allPages = DataStore.getAllPages();
allPages = _.sortBy(allPages, [function(page) { return page.menu_order; }]);

return (
<header>
{allPages.map((page) => {
return <Link key={page.id} to={`/${page.slug}`} style={{marginRight: ’10px’}}>{page.title.rendered}</Link>
})}
</header>
);
}
}

export default Nav;

 

DataStore.getAllPages() will fetch all the pages from WordPress further which we can sort them by “menu_order” with lodash and looping through them to spit out the React Router’s <Link />.
Include the Nav.js component into App.js to witness the dynamic nav included on every page:

import React from ‘react’;
import Nav from ‘./Nav.js’;

export default class App extends React.Component {

constructor(props) {
super(props);
}

render() {
return (
<div className=”wrapper”>
<Nav />
{this.props.children}
</div>
);
}
}

 

It is strongly recommend to refer to official WordPress REST API handbook in order to dig further information about pagination,authentication,querying, creating custom endpoints, CRUD and much more.

 

About Singsys Pte. Ltd. Singsys is a solution provider that offer user friendly solution on cutting edge technologies  to engage customers and boost your brand online results from a set of certified developers, designers who prefer optimized utilization of the available resources to align client’s idea  with their skillset to reflect it into a  Mobile applicationWeb application or an E-commerce solution

 

You may be interested in following:

  1. Create React Native App launched for OS independent React Apps Development

Related Posts...

What is New!