1. Home
  2. Ecommerce Rest Api
  3. React Frontend
  4. Project Setup

Project Setup

1. Set Up Your React App

First, ensure you have Node.js and npm (Node Package Manager) installed. If not, you can download them from nodejs.org.

Create a new React app using Create React App:

npx create-react-app woocommerce-react-app
cd woocommerce-react-app

2. Install Required Packages

You’ll need additional packages to handle environment variables and API requests:

npm install axios dotenv
  • axios: For making HTTP requests.
  • dotenv: For loading environment variables from a .env file.

3. Set Up Environment Variables

Create a .env file in the root of your React projec

REACT_APP_WC_API_URL=https://your-woocommerce-site-url.com/wp-json/wc/v3
REACT_APP_WC_CONSUMER_KEY=your_consumer_key
REACT_APP_WC_CONSUMER_SECRET=your_consumer_secret

Replace https://your-woocommerce-site-url.com with your actual WooCommerce site URL. Obtain your_consumer_key and your_consumer_secret from your WooCommerce site under WooCommerce > Settings > Advanced > REST API.

4. Configure Axios to Use Environment Variables

Create a new file src/api.js to configure Axios with your environment variables:

import axios from 'axios';

const api = axios.create({
  baseURL: process.env.REACT_APP_WC_API_URL,
  auth: {
    username: process.env.REACT_APP_WC_CONSUMER_KEY,
    password: process.env.REACT_APP_WC_CONSUMER_SECRET,
  },
});

export default api;

5. Make API Requests

Now, you can use Axios to make requests to your WooCommerce API endpoints from any React component:

import React, { useState, useEffect } from 'react';
import api from './api';

function App() {
  const [products, setProducts] = useState([]);

  useEffect(() => {
    const fetchProducts = async () => {
      try {
        const response = await api.get('/products');
        setProducts(response.data);
      } catch (error) {
        console.error('Error fetching products:', error);
      }
    };

    fetchProducts();
  }, []);

  return (
    <div>
      <h1>Products</h1>
      <ul>
        {products.map(product => (
          <li key={product.id}>
            {product.name} - ${product.price}
          </li>
        ))}
      </ul>
    </div>
  );
}

export default App;

6. Run Your React App

Start your React app:

npm start

How can we help?