How to Connect WooCommerce with a React Frontend Using the WooCommerce API

Creating a react frontend for our WooCommerce website is more fun. As a frontend made using a JavaScript library we will get more convenience to customize it. Also, we can use all the features, plugins, etc. from our WooCommerce dashboard also. Here in this article, we will discuss the steps to connect a WooCommerce website with a React frontend using the WooCommerce API.

If you are only wanted to integrate the WordPress blog on a React app, I have already created an article on the topic Create A React App On Top Of The WordPress REST API.

Prerequisites

Before starting this article, I assume that the reader is aware of the skills listed below.

  • Using the dashboard of WordPress / WooCommerce
  • Basic website development with React library

What we will learn

Throughout this article, we will learn,

  • To setup the WooCommerce API
  • Creating a new React project
  • Using Bootstrap in our React app
  • Installing packages
  • Integrating WooCommerce API with the React app

Note that we are not setting up a WooCommerce website in this article. Just starting from the WooCommerce dashboard. A WooCommerce app can be set up by creating a WordPress website first and installing the WooCommerge plugin.

Setup the WooCommerce API

Let us first set up the API from the WooCommerce dashboard. There are some steps for setting this up. We need to change the product permalink first and then wanted to generate an API key to get access to our WooCommerce site.

Change product permalinks to custom base

So, log in to your dashboard and navigate to Settings -> Permalinks and at the Product permalinks section, select the Custom base.

Create an API key

We need to create an API key to access the APIs of our WooCommerce website. So let us create one.

Navigate to WooCommerce -> Settings -> Advanced and select the REST API link. We can see the Create an API key button there. Just click on it.

Enter a description, select the user and permissions from there and generate the API key.

This will generate a new Consumer key and Consumer secret for us. Just store these keys somewhere and we will use them in our react app.

Test the API URL

Now, accessing the URL https://yoursite.com/wp-json will return the JSON results like below.

{"name":"Onebest","description":"Just another WordPress site","url":"https:\/\/onebest.in","home":"https:\/\/onebest.in","gmt_offset":"0","timezone_string":"","namespaces":["oembed\/1.0","jetpack\/v4","wpcom\/v2","wc\/store","wc-admin","wc-analytics","wc\/v1","wc\/v2","wc\/v3","wccom-site\/v1","wp\/v2","wp-site-health\/v1"],"authentication":{"application-passwords":{"endpoints":
...

Setup the React Frontend and Integrate the WooCommerce API

Now, let us set the React frontend part. We can create a React project first and integrate the APIs we set up earlier.

Create a new React project

The first step is setting up a React application on your system. This can be easily done using the NPX tool.

So, install Node.js on your system first and create a react application using NPX. Don’t bother about the term NPX, because it’s a tool coming with NPM(Node Package Manager) 5.2+ onwards which will install on your system with Node.js itself.

If you need further assistance in the installation of React on your system, use the below links.

Install React on WindowsUbuntu, and macOS.

npx create-react-app react-woocommerce-rest-api-example

This command will create a react application with the project name react-woocommerce-rest-api-example

Now enter the project directory and start the app.

cd react-woocommerce-rest-api-example
npm start

It will open up the React application we have created in our browser window with the address https://localhost:3000. The port may vary if 3000 is busy.

Now we can use our favorite code editor to edit our project. I personally recommend Visual Studio Code.

Integrate Boostrap in our app

We are using the react-boostrap package for integrating Bootstrap in our React app.

Install the packages React-bootstrap and Bootstrap in our app with the below command.

npm install react-bootstrap@next bootstrap@5.1.1

Now import the boostrap.min.css in the index.js file.

// index.js

import "bootstrap/dist/css/bootstrap.min.css";

Now can use React-bootstrap components inside our React app.

Setup the WooCommerceRestApi

Now, on your react app, install the package WooCommerce REST API using NPM.

npm install --save @woocommerce/woocommerce-rest-api

Import the WooCommerceRestApi and replace the URL, consumerkey and consumersecret with the values we copied earlier.

import WooCommerceRestApi from "@woocommerce/woocommerce-rest-api";

const api = new WooCommerceRestApi({
  url: "http://example.com",
  consumerKey: "ck_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  consumerSecret: "cs_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  version: "wc/v3"
});

Now we can get the data from our WooCommerce website as JSON objects. I have shown an example below to access the orders list.

You could refer to the woocommerce-rest-api-docs page for more API list.

function App() {
  const [orders, setOrders] = useState([]);

  useEffect(() => {
    fetchOrders();
  }, []);

  let fetchOrders = () => {
    api
      .get("orders", {
        per_page: 20,
      })
      .then((response) => {
        if (response.status === 200) {
          setOrders(response.data);
        }
      })
      .catch((error) => {});
  };
...
}

Then we can show this response inside a table In our app.

To convert the time to a readable format, I am using a package called moment also. So install it with the below command.

import moment from "moment";

So that the entire App.js code will look the same as below.

Live demo

I have hosted the created app on firebase for accessing the live app.

https://react-woocommerce-rest-api.web.app/

Codesandbox

Refer to the CodeSandbox link to view the live app. You can clone this project to your CodeSandbox account and edit the code also.

https://codesandbox.io/s/competent-river-7mby0

GitHub

You can always refer to the GitHub repository to clone this project, refer to the code and work on top of it.

https://github.com/techomoro/react-woocommerce-rest-api-example

Summary

Here we discussed the steps to connect WooCommerce with a React frontend using the WooCommerce API. We built an example app and in React JS and also given the GitHub repository and CodeSandBox link.

7 thoughts on “How to Connect WooCommerce with a React Frontend Using the WooCommerce API

  1. hello, first thanks you so much

    second i can’t get it work at my localhost (wordpress and react app)

    i can see with GET method but if a try POST method i get an error

    Access to XMLHttpRequest at ‘http://localhost/wp-json/wc/v3/customers?oauth_consumer_key=ck_84288a9654c8a2824fe301abe6442facaa78944e&oauth_nonce=NrbrUxbNF0i6vsZl8Vh1DrLCqcrdkk1r&oauth_signature_method=HMAC-SHA256&oauth_timestamp=1686973956&oauth_version=1.0&oauth_signature=VijZ2x8phYU7qtQYh3JUS%2Ff5304WmLhBn0OFOr413Fo%3D’ from origin ‘http://localhost:3000’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: It does not have HTTP ok status.

  2. I know this goes without saying, but it’s always worth saying: don’t hardcode your API keys like this (especially when they have read/write access). Your store will get hacked.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.