Learn how to integrate Odoo with the ReactJs interface; It is a top choice for Odoo’s flexible, headless e-commerce solutions.
Introduction
Using Odoo APIs in ReactJs for headless Odoo development enables dynamic content fetching, allowing you to easily pull posts from an Odoo backend.
This approach not only improves SEO but also ensures that your web page is fast and optimized for search engines.
Additionally, APIs facilitate real-time updates and simplify content management without the need to redeploy the application, providing ultimate flexibility to improve the shopping experience.
REST API
The REST API (Representational State Transfer Application Programming Interface) is an architectural style for designing networked applications.
A REST API for a headless ecommerce setup allows different parts of your online store, such as products, orders, and users, to communicate with each other. It uses standard web methods, including:
- GET: Retrieve product details or user information.
- JOB: Create a new order or add a product.
- PUT: Update information about existing products or user profiles.
- DELETE: Remove items from a cart or delete a user account.
It is easier to interact with different services and is widely used for web services due to their simplicity and scalability.
Let’s get started
To integrate Odoo with a React application, create the React application with Tailwind CSS, configure environment variables using a .env
implement a recovery method for the Odoo API and start the development server.
Assumption: We are familiar with the Create React app and you have configured the React app.
Note: We will set up the project with the name “odoo-react-app.“
Step 1: Configure Tailwind CSS
You need to implement Tailwind CSS for effective design of the page UI and its development 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 the 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 the tailwind file base, componentsAnd utilities styles:
@tailwind base; @tailwind components; @tailwind utilities;
Step 2: Configure environment variables
First, we will create the .env file in the 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, for example if you are in production, development, or staging.
- To store sensitive information such as API keys and passwords, which should never be passed to version control.
Open the .env file and set 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: Configure React Query to implement the API.
Use the following command to install the React Query library (TanStack Query) in your application:
npm i @tanstack/react-query
To get things working, use QueryClientProvider
Since @tanstack/react-query
.
Wrap your application, which is the index.js component, with and pass queryClient
as an accessory. It comes automatically from the initialized file QueryClient
.
Open the index.js file and modify the Tanstack Query code. 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: reportWebVitals();
Now that we have done this, we can retrieve the data:
Step 3: Configure React Router
React Router helps you create different pages in your application. 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
Classify and replace the code to import BrowserRouter, Route
And Routes
to display 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 that, you can create the layout to display the components of the pages like Home, Odoo Product, Odoo Customer Cart and Login Page. So create it Layout.js
file in the src/pages
case.
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: Configure the React-Hook-Form component and login page
Integrating React Hook Form into a React application provides a simple and effective 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 is a basic example of how to implement the useform and Odoo APIs by creating 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: Go up to the login page.
Once you have configured the routes and React layout, proceed by opening the App.js
deposit. 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, then check the React app in your browser.
npm run start
Note:- Go to the login page



Mobile view

Conclusion
Congratulations! You have successfully learned how to integrate odoo with ReactJS Frontend.
We will need Webkul Odoo REST APIs for headless development services with Webkul and will check out our Open Source Odoo React headless e-commerce application.
Thank you for reading this blog.
I hope this blog helped you better understand how to integrate odoo with ReactJs Frontend.
Happy coding!!