Learn to combine Odoo with ReactJs frontend; it’s a best choice for versatile, Odoo headless eCommerce options.
Introduction
Utilizing Odoo APIs in ReactJs for a Odoo headless growth permits for dynamic content material fetching, enabling you to simply pull in posts from a Odoo backend.
This method not solely improves search engine optimisation but additionally ensures your webpage is quick and optimized for engines like google.
Furthermore, the APIs facilitate real-time updates and simplify content material administration with out the necessity to redeploy the app, offering final flexibility to reinforce the purchasing expertise.
REST APIs
REST API (Representational State Switch Software Programming Interface) is an architectural fashion for designing networked purposes.
A REST API for a headless eCommerce setup allows completely different components of your on-line retailer comparable to merchandise, orders, and customers to speak with each other. It makes use of normal net strategies, together with:
- GET: Retrieve product particulars or consumer info.
- POST: Create a brand new order or add a product.
- PUT: Replace present product info or consumer profiles.
- DELETE: Take away gadgets from a cart or delete a consumer account.
It simpler to work together with completely different companies, and are broadly used for net companies as a consequence of their simplicity and scalability.
Let’s Begin
To combine Odoo with a React app, create the React app with Tailwind CSS, arrange setting variables utilizing a .env
file, implement a fetcher methodology for Odoo API, and begin the event server.
Assumption: We’re accustomed to the Create React App and you’ve got setup the React Software.
Be aware: We’ll arrange the undertaking with the title “odoo-react-app.“
Step 1: Setup Tailwind CSS
You could implement the Tailwind CSS to efficient web page UI design and its Dev dependencies. Use the next command:
npm set up -D tailwindcss postcss autoprefixer
Run the next command to generate the tailwind.config.js
and postcss.config.js
recordsdata:
npx tailwindcss init -p
Configure Tailwind CSS
Open tailwind.config.js
and replace the content material
array to incorporate paths to your template recordsdata. This permits Tailwind to purge unused types in manufacturing:
/** @sort {import('tailwindcss').Config} */ module.exports = { content material: [ "./src/**/*.{js,jsx,ts,tsx}", // Adjust if needed ], theme: { lengthen: { colours: { major: "#35979C", }, }, }, plugins: [], }
Within the src listing, open the index.css file and add the next strains to import tailwind’s base, parts, and utilities types:
@tailwind base; @tailwind parts; @tailwind utilities;
Step 2: Setup Env Variables
First, We’ll create the .env file in undertaking root listing and now you see the folder construction with Tailwind CSS and the .env file.
. ├── src/ │ ├── App.js │ ├── App.css │ ├── App.take a look at.js | ├── index.js | ├── index.css │ └── brand.svg ├── public/ │ ├── index.html │ ├── brand.svg │ ├── robots.txt │ └── manifest.json ├── package-lock.json ├── .env ├── bundle.json ├── tailwind.config.js └── README.md
Why You Want Atmosphere Variables
- To customise settings based mostly in your setting, like whether or not you’re in manufacturing, growth, or staging.
- To retailer delicate info like API keys and passwords, which ought to by no means be pushed to model management.
Open the .env file and Outline the next setting variable.
REACT_APP_API_URL=<-Odoo-API-Url-> REACT_APP_API_KEY=<-Odoo-API-Authenticate-Key-> REACT_APP_API_VERSION=<-API-Model->
Step 3: Setup React Question to implement API.
Use the next command to put in the React Question library (TanStack Question) in your software:
npm i @tanstack/react-query
To make issues work, use QueryClientProvider
from @tanstack/react-query
.
Wrap your software, which is the index.js part, with it and go queryClient
as a prop. It comes routinely from the initialized QueryClient
.
Open the index.js file and modify the code for Tanstack Question. The index.js file ought to appear to be:
import React from "react"; import ReactDOM from "react-dom/shopper"; 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(doc.getElementById("root")); root.render( <React.StrictMode> <QueryClientProvider shopper={queryClient}> <App /> </QueryClientProvider> </React.StrictMode> ); // If you wish to begin measuring efficiency in your app, go a perform // to log outcomes (for instance: reportWebVitals(console.log)) // or ship to an analytics endpoint. Study extra: https://bit.ly/CRA-vitals reportWebVitals();
Now that we’ve performed this, we will fetch the information:
Step 3: Setup the React Router
React Router helps you create completely different pages in your app. To make use of it, you could set up the React Router library. Merely run the next command in your undertaking folder:
npm set up react-router-dom
Open App.js
File and exchange the code to import BrowserRouter, Route
, and Routes
for displaying the web page part.
import "./App.css"; import { BrowserRouter, Route, Routes } from "react-router-dom"; import Format from "./pages/Format"; perform App() { return ( <> <BrowserRouter> <Routes> <Route path="/" factor={<Format />}> <Route index factor={<h1> dwelling web page </h1>} /> </Route> </Routes> </BrowserRouter> </> ); } export default App;
After this, you may create the format to render parts for pages comparable to House, Odoo Product, Odoo Buyer Cart, and Login Web page. So, create the Format.js
file within the src/pages
folder.
import { Outlet, Hyperlink } from "react-router-dom"; const Format = () => { return ( <> {/* You may add the Header Right here */} <div className="container mx-auto min-h-[50vh]"> <Outlet /> </div> {/* You may add the Footer Right here */} </> ); }; export default Format;
Step 3: Setup React-Hook-Type and Login Web page Part
Integrating React Hook Type right into a React software presents a easy and environment friendly solution to handle kinds
npm set up react-hook-form
Create the Type Part.
We will create a type part that makes use of react-hook-form
. Right here’s a fundamental instance of easy methods to implement useform and Odoo API’s by creating the a file named login.js within the src/pages folder.
import { useMutation } from "@tanstack/react-query"; import React from "react"; import { useForm } from "react-hook-form"; import { Hyperlink } 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 (knowledge) => { const response = await fetch(`${course of.env.REACT_APP_API_URL}api/${course of.env.REACT_APP_API_VERSION}/login`, { methodology: "POST", headers: { "Content material-Kind": "software/json", Authenticate: course of.env.REACT_APP_API_KEY, }, physique: JSON.stringify(knowledge), } ); if (!response.okay) { throw new Error("Community response was not okay"); } return response.json(); // Return the parsed JSON response }, onSuccess: (knowledge) => { if (knowledge?.success) { alert(knowledge?.message); navigate("/"); // Redirect to the house web page } else { alert("login Failed", knowledge?.message); } }, onError: (error) => { alert("Error :", error?.message); }, }); const onSubmit = async (knowledge) => { await mutateAsync(knowledge); }; 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"> <type onSubmit={handleSubmit(onSubmit)} className="bg-white flex flex-col gap-2" > <div className="mb-4"> <label className={labelClass} htmlFor="e-mail"> E-mail: </label> <enter {...register("e-mail", { required: "E-mail is required", sample: { worth: /^[^@ ]+@[^@ ]+.[^@ .]{2,}$/, message: "E-mail shouldn't be legitimate", }, })} sort="e-mail" id="e-mail" className={inputClass} /> {errors.e-mail && ( <p className="text-red-500">{errors.e-mail.message}</p> )} </div> <div className="mb-4"> <label className={labelClass} htmlFor="password"> Password: </label> <enter {...register("password", { required: "password is required", })} sort="password" id="password" className={inputClass} /> {errors.e-mail && ( <p className="text-red-500">{errors.password.message}</p> )} </div> <button sort="submit" className="w-full py-2 bg-primary duration-300 text-white rounded hover:bg-primary/90" > Login </button> </type> <div className="flex justify-between my-3"> <Hyperlink to="net/signup" className="text-cyan-800 text-sm"> Do not have an account </Hyperlink> <Hyperlink to="net/reset_password" className="text-cyan-800 text-sm"> Reset password </Hyperlink> </div> <div className="text-center"> <span className="text-sm text-center text-cyan-800"> <i>-Or-</i> </span> <button sort="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 Web page.
After you have arrange the React routes and format, proceed by opening the App.js
file. On this file, embrace the login part within the routes to allow navigation to the login web page.
import "./App.css"; import { BrowserRouter, Route, Routes } from "react-router-dom"; import Format from "./pages/Format"; import LoginPage from "./pages/Login"; perform App() { return ( <> <BrowserRouter> <Routes> <Route path="/" factor={<Format />}> <Route index factor={<h1> dwelling web page </h1>} /> <Route path="net/login" factor={<LoginPage />} /> </Route> </Routes> </BrowserRouter> </> ); } export default App;
Step 5: Run your React app.
Run the next command to see the cart web page within the terminal, after which test the React app in your browser.
npm run begin

Be aware:- Navigate to login web page at http://localhost:3000/net/login



Cellular View

Conclusion
Congratulations! You’ve efficiently discover ways to combine odoo with ReactJS Frontend.
We would require the Webkul Odoo REST APIs for headless growth companies with Webkul and take a look at our Open Supply Odoo React headless eCommerce Software
Thanks for studying this weblog.
Hope this weblog helped you to higher perceive easy methods to combine odoo with ReactJs Frontend.
Comfortable Coding!!