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

Last Updated on May 5, 2021 by admin

In this blog, I will explain to you how to create a single-page application for todo lists using React js and WordPress REST API. Create a Single Page Application With React js and WordPress REST API

Create custom post type for todo lists in WordPress

Note: I am using the default twenty nineteen themes provided by WordPress but you can also use your custom theme.

We will not use default posts of WordPress for our to-do lists.

So let’s create a custom post type named todo list. Open your functions.php file and add the 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 a front-end form from where user can enter their details like task name, task description etc.

Let’s create a 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:

Create a custom endpoint for REST API

Next, we need to create a custom endpoint for our custom post type to access our post types data. So, open the functions.php file and add the 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, a new folder will be created in your system with your selected name. You also need to install another important package named Axios. To install it, run the command npm install axios. You can get more information here.

It’s time to unlock the power of React

After installing react app, open the app.js file in your favorite code editor. You can also create your own js file and import it into 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(
'<a href="https://localhost/gutenberg-demo/wp-json/sections/v1/todo-list">https://localhost/gutenberg-demo/wp-json/sections/v1/todo-list</a>
);
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 this:

Read more: wordpress rest api with python

You can check the code for more information on my Github.

Leave a Comment