Back to Top

How to integrate Odoo with ReactJs frontend

Updated 24 October 2024

Learn how to integrate Odoo with ReactJs frontend; it’s a top choice for flexible, Odoo headless eCommerce solutions.

Introduction

Using Odoo APIs in ReactJs for a Odoo headless development allows for dynamic content fetching, enabling you to easily pull in posts from a Odoo backend.

This approach not only improves SEO but also ensures your webpage is fast and optimized for search engines.

Moreover, the APIs facilitate real-time updates and simplify content management without the need to redeploy the app, providing ultimate flexibility to enhance the shopping experience.

REST APIs

REST API (Representational State Transfer Application Programming Interface) is an architectural style for designing networked applications.

Searching for an experienced
Odoo Company ?
Find out More

A REST API for a headless eCommerce setup enables different parts of your online store such as products, orders, and users to communicate with one another. It utilizes standard web methods, including:

  • GET: Retrieve product details or user information.
  • POST: Create a new order or add a product.
  • PUT: Update existing product information or user profiles.
  • DELETE: Remove items from a cart or delete a user account.

It easier to interact with different services, and are widely used for web services due to their simplicity and scalability.

Let’s Start

To integrate Odoo with a React app, create the React app with Tailwind CSS, set up environment variables using a .env file, implement a fetcher method for Odoo API, and start the development server.

Assumption: We’re familiar with the Create React App and you have setup the React Application.

Note: We will set up the project with the name “odoo-react-app.

Step 1: Setup Tailwind CSS

You need to implement the Tailwind CSS to effective page UI design and its Dev dependencies. Use the following command:

npm install -D tailwindcss postcss autoprefixer

Run the following command to generate the tailwind.config.js and postcss.config.js files:

npx tailwindcss init -p

Configure Tailwind CSS

Open tailwind.config.js and update the content array to include paths to your template files. This allows Tailwind to purge unused styles in production:

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    "./src/**/*.{js,jsx,ts,tsx}", // Adjust if needed
  ],
  theme: {
    extend: {
       colors: {
          primary: "#35979C",
      },
    },
  },
  plugins: [],
}

In the src directory, open the index.css file and add the following lines to import tailwind’s base, components, and utilities styles:

@tailwind base;
@tailwind components;
@tailwind utilities;

Step 2: Setup Env Variables

First, We’ll create the .env file in project root directory and now you see the folder structure with Tailwind CSS and the .env file.

.
├── src/
│   ├── App.js
│   ├── App.css
│   ├── App.test.js
|   ├── index.js
|   ├── index.css
│   └── logo.svg
├── public/
│   ├── index.html
│   ├── logo.svg
│   ├── robots.txt
│   └── manifest.json
├── package-lock.json
├── .env
├── package.json
├── tailwind.config.js
└── README.md

Why You Need Environment Variables

  • To customize settings based on your environment, like whether you’re in production, development, or staging.
  • To store sensitive information like API keys and passwords, which should never be pushed to version control.

Open the .env file and Define the following environment variable.

REACT_APP_API_URL=<-Odoo-API-Url->
REACT_APP_API_KEY=<-Odoo-API-Authenticate-Key->
REACT_APP_API_VERSION=<-API-Version->

Step 3: Setup React Query to implement API.

Use the following command to install the React Query library (TanStack Query) in your application:

npm i @tanstack/react-query

To make things work, use QueryClientProvider from @tanstack/react-query.

Wrap your application, which is the index.js component, with it and pass queryClient as a prop. It comes automatically from the initialized QueryClient.

Open the index.js file and modify the code for Tanstack Query. The index.js file should look like:

import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
const queryClient = new QueryClient();

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <React.StrictMode>
    <QueryClientProvider client={queryClient}>
      <App />
    </QueryClientProvider>
  </React.StrictMode>
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

Now that we have done this, we can fetch the data:

Step 3: Setup the React Router

React Router helps you create different pages in your app. To use it, you need to install the React Router library. Simply run the following command in your project folder:

npm install react-router-dom

Open App.js File and replace the code to import BrowserRouterRoute, and Routes for displaying the page component.

import "./App.css";
import { BrowserRouter, Route, Routes } from "react-router-dom";
import Layout from "./pages/Layout";

function App() {
  return (
    <>
      <BrowserRouter>
        <Routes>
          <Route path="/" element={<Layout />}>
            <Route index element={<h1> home page </h1>} />
          </Route>
        </Routes>
      </BrowserRouter>
    </>
  );
}

export default App;

After this, you can create the layout to render components for pages such as Home, Odoo Product, Odoo Customer Cart, and Login Page. So, create the Layout.js file in the src/pages folder.

import { Outlet, Link } from "react-router-dom";

const Layout = () => {
  return (
    <>
       {/* You can add the Header Here */}
      <div className="container mx-auto min-h-[50vh]">
        <Outlet />
      </div>
      {/* You can add the Footer Here */}
    </>
  );
};

export default Layout;

Step 3: Setup React-Hook-Form and Login Page Component

Integrating React Hook Form into a React application offers a simple and efficient way to manage forms

npm install react-hook-form

Create the Form Component.

We can create a form component that uses react-hook-form. Here’s a basic example of how to implement useform and Odoo API’s by creating the a file named login.js in the src/pages folder.

import { useMutation } from "@tanstack/react-query";
import React from "react";
import { useForm } from "react-hook-form";
import { Link } from "react-router-dom";
import { useNavigate } from "react-router-dom";

const LoginPage = () => {
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm();
  const navigate = useNavigate();

  const { mutateAsync } = useMutation({
    mutationFn: async (data) => {
      const response = await fetch(`${process.env.REACT_APP_API_URL}api/${process.env.REACT_APP_API_VERSION}/login`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            Authenticate: process.env.REACT_APP_API_KEY,
          },
          body: JSON.stringify(data),
        }
      );
      if (!response.ok) {
        throw new Error("Network response was not ok");
      }

      return response.json(); // Return the parsed JSON response
    },
    onSuccess: (data) => {
      if (data?.success) {
        alert(data?.message);
        navigate("/"); // Redirect to the home page
      } else {
        alert("login Failed", data?.message);
      }
    },
    onError: (error) => {
      alert("Error :", error?.message);
    },
  });

  const onSubmit = async (data) => {
    await mutateAsync(data);
  };

  const inputClass =
    "block bg-slate-50 w-full rounded border border-solid outline-none px-3 py-2 border-border-gray placeholder-slate-400  ring-transparent focus:border-primary focus:ring-primary";
  const labelClass =
    "block mb-2 text-slate-900  text-base tracking-wide font-semibold";

  return (
    <>
      <div className="flex flex-col items-center justify-center w-full mt-10 mb-10 sm:mb-0">
        <div className="w-80 px-4">
          <form
            onSubmit={handleSubmit(onSubmit)}
            className="bg-white flex flex-col gap-2"
          >
            <div className="mb-4">
              <label className={labelClass} htmlFor="email">
                Email:
              </label>
              <input
                {...register("email", {
                  required: "Email is required",
                  pattern: {
                    value: /^[^@ ]+@[^@ ]+\.[^@ .]{2,}$/,
                    message: "Email is not valid",
                  },
                })}
                type="email"
                id="email"
                className={inputClass}
              />
              {errors.email && (
                <p className="text-red-500">{errors.email.message}</p>
              )}
            </div>
            <div className="mb-4">
              <label className={labelClass} htmlFor="password">
                Password:
              </label>
              <input
                {...register("password", {
                  required: "password is required",
                })}
                type="password"
                id="password"
                className={inputClass}
              />
              {errors.email && (
                <p className="text-red-500">{errors.password.message}</p>
              )}
            </div>
            <button
              type="submit"
              className="w-full py-2 bg-primary duration-300 text-white rounded hover:bg-primary/90"
            >
              Login
            </button>
          </form>
          <div className="flex justify-between my-3">
            <Link to="web/signup" className="text-cyan-800 text-sm">
              Don't have an account
            </Link>
            <Link to="web/reset_password" className="text-cyan-800 text-sm">
              Reset password
            </Link>
          </div>
          <div className="text-center">
            <span className="text-sm text-center  text-cyan-800">
              <i>-Or-</i>
            </span>
            <button
              type="submit"
              className="w-full py-2 px-4 text-start border border-solid bg-white hover:bg-gray-100 duration-300 rounded "
            >
              Login with Odoo.com
            </button>
          </div>
        </div>
      </div>
    </>
  );
};

export default LoginPage;

Step 4: Mount the Login Page.

Once you have set up the React routes and layout, proceed by opening the App.js file. In this file, include the login component in the routes to enable navigation to the login page.

import "./App.css";
import { BrowserRouter, Route, Routes } from "react-router-dom";
import Layout from "./pages/Layout";
import LoginPage from "./pages/Login";

function App() {
  return (
    <>
      <BrowserRouter>
        <Routes>
          <Route path="/" element={<Layout />}>
            <Route index element={<h1> home page </h1>} />
            <Route path="web/login" element={<LoginPage />} />
          </Route>
        </Routes>
      </BrowserRouter>
    </>
  );
}
export default App;

Step 5: Run your React app.

Run the following command to see the cart page in the terminal, and then check the React app in your browser.

npm run start
Terminal Output for start development server for odd React frontend

Note:- Navigate to login page at http://localhost:3000/web/login

Odoo React frontend output.
login success output for odoo React Frontend.
Login failed output for Odoo React Frontend
Mobile view Login output for Odoo ReactJs Frontend

Conclusion

Congratulations! You’ve successfully learn how to integrate odoo with ReactJS Frontend.

We will require the Webkul Odoo REST APIs for headless development services with Webkul and check out our Open Source Odoo React headless eCommerce Application

Thanks for reading this blog.

Hope this blog helped you to better understand how to integrate odoo with ReactJs Frontend.

Happy Coding!!

. . .

Leave a Comment

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


Be the first to comment.

Back to Top

Message Sent!

If you have more details or questions, you can reply to the received confirmation email.

Back to Home