New Self New Life
No Result
View All Result
  • Home
  • Entertainment
  • Celebrity
  • Cinema
  • Music
  • Digital Lifestyle
  • Social Media
  • Softwares
  • Devices
  • Home
  • Entertainment
  • Celebrity
  • Cinema
  • Music
  • Digital Lifestyle
  • Social Media
  • Softwares
  • Devices
New Self New Life
No Result
View All Result
Home Softwares

ReactJs | How to create Magento 2 product page using ReactJS

by admin
8 months ago
in Softwares
ReactJs | How to create Magento 2 product page using ReactJS
Share on FacebookShare on Twitter


Discover ways to construct a Magento 2 product web page utilizing ReactJs in a headless improvement surroundings.

By leverage of headless structure, we’ll seamlessly combine Magento 2 backend with React, permitting for a extra versatile and dynamic person expertise and the total potential of headless commerce.

Introduction

Making a product web page in React to your Magento 2 retailer can considerably affect whether or not a person decides to purchase your product or transfer on.

This information will take you thru the method of constructing an environment friendly and user-friendly product web page, that includes code examples and detailed explanations.

You’ll achieve helpful insights into React.js improvement alongside the best way.

You’ll discover ways to fetch knowledge from Magento 2 GraphQL API, handle state, and design a responsive structure that enhances the general purchasing expertise.

Magento Product Page with ReactJs

Implementation

Now, let’s implement the product web page step-by-step.

Setting Up Your Product Web page with ReactJs

1. Create Your ReactJs Venture:

Open your terminal and run the next command to create a brand new React.Js Venture

npx create-react-app my-magento-store
cd my-magento-store

2. Navigate to root listing:

cd my-magento-store

3. Set up Crucial Packages In Your ReactJs:

As, I created this with Tailwind, Eslint, React router dom, TypeScript so:

// typescript and eslint
npm set up -D typescript eslint

// tailwind css
npm set up -D tailwindcss postcss autoprefixer
npx tailwindcss init -p

// react router
npm set up react-router-dom

4. Set Up GraphQL Queries:

As we’re utilizing Magento 2 GraphQl API. So lets, create a folder to your GraphQL queries. This retains your code organized.

mkdir src/graphql
contact src/graphql/queries.ts
//In queries.ts, you may outline your GraphQL question for fetching product particulars:
// graphql/queries.ts

export const GET_PRODUCT_BY_SKU = (sku: string) => `
{
    merchandise(filter: {sku: {eq: "${sku}"}}) {
        gadgets {
            id
            identify
            rating_summary
            review_count
            sku
            stock_status
            value {
                regularPrice {
                    quantity {
                        worth
                        foreign money
                    }
                }
            }
            description {
                html
            }
            media_gallery {
                url
            }
        }
    }
}
`;

5. Create Your Product Web page In ReactJs:

Contained in the src listing, in a file referred to as App.tsx add routing construction:

import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import ProductPage from '../parts/ProductPage'; // Your product web page element

perform App() {
  return (
    <Router>
      <Routes>
        <Route path="/product/:sku" element={ProductPage} />
        {/* Different routes */}
      </Routes>
    </Router>
  );
}

export default App;

6. Create a product web page element

mkdir src/parts
contact src/parts/ProductPage.tsx

And, add the next code in product web page element:

import React, { useEffect, useState } from "react";
import { GET_PRODUCT_BY_SKU } from "../graphql/queries";
import { StarIcon } from "./StarIcon";
import { HeartIcon } from "./Coronary heart";
import { ChartBarIcon } from "./CompareIcon";
import { useParams } from "react-router-dom";
interface ProductType {
  value: any;
  media_gallery: {
    url: string;
  }[];
  identify: string;
  stock_status: string;
  sku: string;
  id: string;
}
const ProductPage: React.FC = () => {
  const { sku="" } = useParams<{ sku: string }>();
  const [product, setProduct] = useState<ProductType | null>(null);
  const [loading, setLoading] = useState(true);
  const APP_URL = MAGENTO_ENDPOINT/graphql;
  useEffect(() => {
    const fetchProduct = async () => {
      strive {
        const res = await fetch("APP_URL", {
          methodology: "POST",
          headers: {
            "Content material-Kind": "utility/json",
          },
          physique: JSON.stringify({
            question: GET_PRODUCT_BY_SKU(sku),
          }),
        });

        const knowledge = await res.json();
        const fetchedProduct = knowledge.knowledge.merchandise.gadgets[0] || null;
        setProduct(fetchedProduct);
      } catch (error) {
        console.error(error);
      } lastly {
        setLoading(false);
      }
    };

    fetchProduct();
  }, [sku]);

  if (loading) {
    return <div>Loading...</div>;
  }

  if (!product) {
    return <div>No product discovered.</div>;
  }

  const priceData = product.value.regularPrice.quantity;
  const foreign money = "USD";
  const worth = priceData?.worth;
  const value = worth?.toLocaleString("en-US", {
    type: "foreign money",
    foreign money,
  });
  const gadgets = new Array(5).fill(0);

  return (
       <div className="container relative grid items-start p-3 mx-auto font-sans sm:p-6 lg:grid-cols-12">
      {product.media_gallery && product.media_gallery.size > 0 && (
        <img
          src={product.media_gallery[0].url}
          className="relative object-contain w-screen h-full lg:col-span-7 lg:max-w-4xl aspect-square"
          alt={product.identify}
        />
      )}
      <div className="flex flex-col gap-6 mt-5 lg:col-span-5">
        <h1 className="text-4xl lg:text-6xl font-extralight">{product.identify}</h1>
        <div className="flex items-center gap-10">
          <div className="flex items-center">
            {gadgets.map((score) => (
              <StarIcon
                key={score}
                className={`${3 > score ? "text-yellow-500 fill-yellow-500" : "text-gray-200"} h-5 w-5 flex-shrink-0`}
                aria-hidden="true"
              />
            ))}
          </div>
          <p className="text-sm font-medium cursor-pointer md:text-base text-sky-600 hover:text-sky-700">{merchandise.review_count} Evaluations</p>
          <p className="text-sm font-medium cursor-pointer md:text-base text-sky-600 hover:text-sky-700">Add Your Evaluate</p>
        </div>
        <div className="flex items-start justify-between">
          <h2 className="text-3xl font-medium lg:text-5xl lg:font-semibold">{value}</h2>
          <div>
            <p className="font-semibold">{product?.stock_status?.substitute("_", " ")}</p>
            <p>Sku# : {product?.sku}</p>
          </div>
        </div>
        <hr className="w-full h-px border border-gray-200" />
        <div className="flex flex-col gap-px">
          <p className="font-normal">Qty:</p>
          <enter
            className="p-2 border border-gray-400 rounded-lg max-w-16"
            defaultValue={1}
            kind="quantity"
            min="1"
            max="100"
          />
        </div>
        <button className="w-full px-8 py-4 text-xl font-semibold text-white duration-200 lg:max-w-60 bg-sky-600 hover:bg-sky-700">
          Add to Cart
        </button>
        <div className="flex items-center gap-12">
          <button className="flex items-center justify-center w-full gap-3 text-sm font-semibold text-gray-500 uppercase cursor-pointer md:text-base max-w-fit">
            <HeartIcon className="w-5 h-5 -mt-px text-gray-500" />
            Add to wishlist
          </button>
          <button className="flex items-center justify-center w-full gap-3 text-sm font-semibold text-gray-500 uppercase cursor-pointer md:text-base max-w-fit">
            <ChartBarIcon className="w-5 h-5 -mt-px fill-gray-500" />
            Add to match
          </button>
        </div>
      </div>
    </div>
  );
};

export default ProductPage;
react.js product page desktop view

MObile View

react.js product page mobile view

7. Run Your Software:

Lastly, run your ReactJs app to see your product web page in motion:

npm begin

Conclusion

By following these steps, you’ve efficiently created a product web page utilizing React.Js that integrates seamlessly together with your Magento 2 backend.

This basis not solely shows important product data but additionally units the stage for additional enhancements.

You’ll be able to elevate the person expertise by including options comparable to a buyer cart, person evaluations, associated merchandise, and superior styling choices.

These additions won’t solely enrich the performance but additionally create a extra participating purchasing expertise to your clients.

Be at liberty to customise and increase upon this basis as wanted, tailoring it to fulfill your particular enterprise targets and person wants. The probabilities are limitless!

author-thumb



Source link

Tags: CreateMagentopageproductReactjs
Previous Post

Prince Collaborator Cat Glover Dead at 60

Next Post

Sidec Twin Accelerator aims to grow startups & SMEs in M’sia

Related Posts

How to Add Custom Style Variations to WordPress Blocks — Speckyboy
Softwares

How to Add Custom Style Variations to WordPress Blocks — Speckyboy

by admin
June 2, 2025
Smart software replaces expensive sensors for glass wall detection with 96% accuracy
Softwares

Smart software replaces expensive sensors for glass wall detection with 96% accuracy

by admin
June 1, 2025
User Guide For UnoPim PDF Generator
Softwares

User Guide For UnoPim PDF Generator

by admin
May 31, 2025
Infragistics Ultimate 25.1 includes updates across several of its UI toolkit components
Softwares

Infragistics Ultimate 25.1 includes updates across several of its UI toolkit components

by admin
May 29, 2025
Qt bridges the language barrier gap
Softwares

Qt bridges the language barrier gap

by admin
May 28, 2025
Next Post
Sidec Twin Accelerator aims to grow startups & SMEs in M’sia

Sidec Twin Accelerator aims to grow startups & SMEs in M'sia

Gabby Logan shares emotional family update in rare post with daughter Lois

Gabby Logan shares emotional family update in rare post with daughter Lois

  • Trending
  • Comments
  • Latest
Anant Ambani wedding: Celebs, wealthy elite attend lavish billionaire festivities – National

Anant Ambani wedding: Celebs, wealthy elite attend lavish billionaire festivities – National

March 1, 2024
Product Information Management Trends (PIM)

Product Information Management Trends (PIM)

February 4, 2022
Every Kathryn Hahn Film Performance, Ranked

Every Kathryn Hahn Film Performance, Ranked

December 24, 2022
Deployment Diagrams Explained in Detail, With Examples

Deployment Diagrams Explained in Detail, With Examples

August 11, 2021
How to Build a JavaScript Search [Article]

How to Build a JavaScript Search [Article]

August 30, 2022
How to Build a DIY Spotify Music Player with Raspberry Pi Pico

How to Build a DIY Spotify Music Player with Raspberry Pi Pico

May 13, 2025
J & G Thomson & Co Whisky & Spirits Review

J & G Thomson & Co Whisky & Spirits Review

December 22, 2021
Advancement in predicting software vulnerabilities

Advancement in predicting software vulnerabilities

May 21, 2022
May 30-June 1 Box Office Recap – ‘Lilo & Stitch’ crosses $600M worldwide, while ‘Mission: Impossible – The Final Reckoning’ crosses $350M worldwide. ‘Karate Kid: Legends’ and ‘Bring Her Back’ have solid debuts, while ‘The Phoenician Scheme’ opens with the best per-theater average ($93K) of the year.

May 30-June 1 Box Office Recap – ‘Lilo & Stitch’ crosses $600M worldwide, while ‘Mission: Impossible – The Final Reckoning’ crosses $350M worldwide. ‘Karate Kid: Legends’ and ‘Bring Her Back’ have solid debuts, while ‘The Phoenician Scheme’ opens with the best per-theater average ($93K) of the year.

June 3, 2025
Samsung may incorporate Perplexity’s AI tech in its phones

Samsung may incorporate Perplexity’s AI tech in its phones

June 2, 2025
Sammy Hagar and Eddie Van Halen Wanted to Write Song on Cello

Sammy Hagar and Eddie Van Halen Wanted to Write Song on Cello

June 2, 2025
Lady Isabella Hervey on bouncing back from her unhappy marriage and her new life on the Algarve

Lady Isabella Hervey on bouncing back from her unhappy marriage and her new life on the Algarve

June 2, 2025
19 Sustainable Clothing Brands For Stylish Men In 2025

19 Sustainable Clothing Brands For Stylish Men In 2025

June 2, 2025
How to Add Custom Style Variations to WordPress Blocks — Speckyboy

How to Add Custom Style Variations to WordPress Blocks — Speckyboy

June 2, 2025
Instagram Creators With Over 100K Followers Will Get Access to Additional Comment Filters

Instagram Creators With Over 100K Followers Will Get Access to Additional Comment Filters

June 2, 2025
Fantastic Four Star Vanessa Kirby Is Pregnant!

Fantastic Four Star Vanessa Kirby Is Pregnant!

June 2, 2025
New Self New Life

Your source for entertainment news, celebrities, celebrity news, and Music, Cinema, Digital Lifestyle and Social Media and More !

Categories

  • Celebrity
  • Cinema
  • Devices
  • Digital Lifestyle
  • Entertainment
  • Music
  • Social Media
  • Softwares
  • Uncategorized

Recent Posts

  • May 30-June 1 Box Office Recap – ‘Lilo & Stitch’ crosses $600M worldwide, while ‘Mission: Impossible – The Final Reckoning’ crosses $350M worldwide. ‘Karate Kid: Legends’ and ‘Bring Her Back’ have solid debuts, while ‘The Phoenician Scheme’ opens with the best per-theater average ($93K) of the year.
  • Samsung may incorporate Perplexity’s AI tech in its phones
  • Sammy Hagar and Eddie Van Halen Wanted to Write Song on Cello
  • Home
  • Disclaimer
  • DMCA
  • Privacy Policy
  • Cookie Privacy Policy
  • Terms and Conditions
  • Contact us

Copyright © 2021 New Self New Life.
New Self New Life is not responsible for the content of external sites. slotsfree  creator solana token

No Result
View All Result
  • Home
  • Entertainment
  • Celebrity
  • Cinema
  • Music
  • Digital Lifestyle
  • Social Media
  • Softwares
  • Devices

Copyright © 2021 New Self New Life.
New Self New Life is not responsible for the content of external sites.

funbingo.bet