WordPress Post from Front End using REST API and React

This post is a proof of concept for using the WordPress REST API to demonstrate how to build CRUD (Create, Read, Update, and Delete) functionality within a React application running on a frontend WordPress page.

Plugin Source

Clone into the plugins folder of your local WordPress instance. for example,

cd wordpress/wp-content/plugins

git clone https://github.com/jimfrenette/wp-api-react-poc.git

After cloning into the plugins folder, you may activate the plugin.

Activate the WP API React Proof of Concept plugin

Plugin Frontend Build

cd wp-api-react-poc

# install node modules
npm install

# build
npm run build

Code Highlights

WP Scripts is used to build our React app with Webpack. A webpack config in the top-level directory of the plugin package will be used if it finds one. If none is found, it’ll use the default config provided by @wordpress/scripts. Learn more in the Advanced Usage section.

Our webpack config, webpack.config.js makes React and ReactDOM available outside of the bundle to prevent import errors when using 3rd party React libs. For example,

const defaults = require("@wordpress/scripts/config/webpack.config");

module.exports = {
  ...defaults,
  externals: {
    "react": "React",
    "react-dom": "ReactDOM"
  }
};

The React Hooks pattern is being used in our React app code instead of classes.

Page Slug

From the menu, select New > Page

For the title, enter api-react.

Publish the new api-react page.

To use this in another page, customize the name of the page slug in the class-api-rpoc-page.php plugin class file. e.g.,

class-api-rpoc-page.php
private static $page_slug = 'api-react';

This proof-of-concept was tested with WordPress permalink settings set to Post name.

Manually refresh the api-react page to verify the build. You should now have a working front end form to Submit a New Post, Edit existing posts or Delete posts. If you delete a post, don’t worry, you can restore it from the trash within the admin dashboard.

Versions that were used in this proof-of-concept.

  • @WordpressScripts 19.2.2
  • WordPress 5.8.2

Source Code

Resources

comments powered by Disqus