Create a Single Page Application With React js and WordPress REST API

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 the default twenty nineteen 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 a new page from the WordPress admin panel and apply your template to it. Open that page in the browser it will look like this:

whole blogs todo list

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 Application

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 the 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(
'https://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 https://localhost:3000 in any browser to view your todo list. I have added some bit of CSS. It will look like:

whole blogs

You can check code for more information on my github.

Comments

    1. Post
      Author
    1. Post
      Author
  1. Justin

    Long time supporter, and thought I’d drop
    a comment.

    Your wordpress site is very sleek – hope you don’t mind me
    asking what theme you’re using? (and don’t mind if I steal it?

    :P)

    I just launched my site –also built in wordpress like yours–
    but the theme slows (!) the site down quite a bit.

    In case you have a minute, you can find it by searching for “royal cbd” on Google (would appreciate
    any feedback) – it’s still in the works.

    Keep up the good work– and hope you all take care of yourself during the coronavirus scare!

    1. Post
      Author
      Whole blogs

      @justin
      First of all thanks for reading my blogs. As you mentioned that your WordPress site is slowed. There are several techniques you need to follow to improve your site speed. Give me some time and I will back with one blog for improving the speed of WordPress site.
      Thanks once again!!!!

Leave a Reply

Your email address will not be published. Required fields are marked *