How to Create a Single Page Application(SPA) With React js and WordPress REST API

Brijesh Dhanani
4 min readJan 22, 2020

In this blog I will explain you how to create a single page application for todo lists using React js and WordPress REST API.

Create custom post type for todo lists in WordPress

Note: I am using default twentynineteen theme provided by WordPress but you can also use your custom theme.

We will not use default posts of WordPress for our todo lists. So let’s create custom post type named todo list. Open your functions.php file and add following code inside it:

add_action( 'init', 'todo_list' );
/**
* Register a Todo-Lists post type.
*/
function todo_list() {
$labels = array(
'name' => _x( 'Todo-Lists', 'post type general name', 'customtheme' ),
'singular_name' => _x( 'Todo-list', 'post type singular name', 'customtheme' ),
'menu_name' => _x( 'Todo-Lists', 'admin menu', 'customtheme' ),
'name_admin_bar' => _x( 'Todo-list', 'add new on admin bar', 'customtheme' ),
'add_new' => _x( 'Add New', 'Todo-list', 'customtheme' ),
'add_new_item' => __( 'Add New Todo-Lists', 'customtheme' ),
'new_item' => __( 'New Todo-list', 'customtheme' ),
'edit_item' => __( 'Edit Todo-list', 'customtheme' ),
'view_item' => __( 'View Todo-list', 'customtheme' ),
'all_items' => __( 'All Todo-Lists', 'customtheme' ),
'search_items' => __( 'Search Todo-Lists', 'customtheme' ),
'parent_item_colon' => __( 'Parent Todo-Lists:', 'customtheme' ),
'not_found' => __( 'No Todo-Lists found.', 'customtheme' ),
'not_found_in_trash' => __( 'No Todo-Lists found in Trash.', 'customtheme' )
);
$args = array(
'labels' => $labels,
'description' => __( 'Description.', 'customtheme' ),
'public' => true,
'publicly_queryable' => false,
'show_ui' => true,
'show_in_menu' => true,
'query_var' => true,
'rewrite' => array( 'slug' => 'todo-list', 'with_front' => false ),
'capability_type' => 'post',
'has_archive' => false,
'hierarchical' => false,
'menu_position' => null,
'supports' => array( 'title', 'editor', 'author', 'thumbnail')
);
register_post_type( 'todo-list', $args );
}

Create front end form

Now we will create front end form from where user can enter their details like task name, task description etc. Let’s create new template file for that. In this template file, we will add code for custom form to display it in WordPress front end for data insertion.

<?php
/**
* The template name: Front-End Post
*
*/
get_header(); ?>
<?php
$page_id = get_queried_object()->ID;
$page_url = get_permalink(get_queried_object()->ID);
?>
<div id="primary" class="content-area" style=" width: 800px;margin: -73px 215px 0px;" ><h2>Todo List</h2>
<form method="post" action="<?php echo $page_url; ?>">
<div class="form-group">
<label for="title">Task Title:</label>
<br>
<input type="text" class="form-control" id="title" name="title" style="width: 100%;">
</div>

<div class="form-group">
<label for="pwd">Task Description :</label>
<textarea class="form-control" name="description"></textarea>
</div>
<br>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div><?php
get_footer();

Now, create new page from WordPress admin panel and apply your template to it. Open that page in browser it will look like this:

Create custom endpoint for REST API

Next, we need to create custom endpoint for our custom post type to access our post types data. So, open functions.php file and add below code in it.

function  sections_endpoint( $request_data ) {
$args = array(
'post_type' => 'todo-list',
'posts_per_page'=>-1,
'numberposts'=>-1
);
$posts = get_posts($args);
foreach ($posts as $key => $post) {
$posts[$key]->post_title;
$posts[$key]->post_content;
}
return $posts;
}
add_action( 'rest_api_init', function () {
register_rest_route( 'sections/v1', '/todo-list/', array(
'methods' => 'GET',
'callback' => 'sections_endpoint'
));
});

Create React Applicatipon

We will first install the create-react-app globally. Then we create a project using create-react-app command.

npm install -g create-react-app
create-react-app yourprojectname
cd yourprojectname
npm run start

After running above command, new folder will be created in your system with your selected name. You also need to install one another important package named axios. To install it, run command npm install axios. You can get more information here.

It’s time to unlock the power of React

After installing react app, open app.js file in your favourite code editor. You can also create your own js file and import it in your index.js file. Open your js file and add code for accessing the todo lists that you have created using WordPress.

import React, { Fragment } from "react";
import axios from "axios";
import "./App.css";
import {
BrowserRouter as Router,
} from "react-router-dom";
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
posts: []
};
}
getAllPosts = async () => {
let responce = await axios.get(
'http://localhost/gutenberg-demo/wp-json/sections/v1/todo-list'
);
let { data } = await responce;
this.setState({ posts: data });
};
componentDidMount = async () => {
await this.getAllPosts();
};
render() {
const { posts } = this.state;
return (
<Router>
<Fragment>
{/* Links */}
<div className="container">
<div className="wrap-list">
{posts.map((page, index) => {
return (
<>
<div className="wrap-input">
<input type="checkbox" name={page.post_title} value={page.post_title} />
<h2 className={"post-title"}>{page.post_title}</h2>
<div className={"post-content"}>{page.post_content}</div>
</div>
</>
);
})}
</div>
</div>
</Fragment>
</Router>
);
}
}

Now, open http://localhost:3000 in any browser to view your todo list. I have added some bit of css. It will look like:

You can check code for more information on my Github.

https://github.com/BRdhanani/spa-with-reactjs-wordpress-rest-api

Check out wholeblogs.com for more references and blogs.

--

--

Brijesh Dhanani

👤 Software Engineer at Publicis Sapient, Singer, Blogger, React, JQuery, Node, Javascript. https://brdhanani.github.io