PWA

How to modify React Components in Magento 2 PWA

In Magento2, we can add/delete/modify views and layouts by overriding Layout XMLs and Templates. In PWA studio, we can achieve that feature using TargetableReactComponent. This component is used to add, delete, modify or replace React Components of the Venia UI storefront. You can review the document for the use of TargetableReactComponent from the following path in your PWA Studio folder structure:
pwa-devdocs/src/pwa-buildpack/reference/targetables/TargetableReactComponent/index.md

Identify React component hierarchies

You can use React Developer Tool to inspect React components. Install React Developer Tools in Chrome browser. After installation, you would get new tabs named “Components” and “Profiler” in your Chrom DevTools. It shows the root React component and its subcomponents. By inspecting any React component you can view and edit its props and state on the right-side panel.

Let’s take an example to add a custom blog before the footer section. For that, you need to create a custom component, add it Main Component before Footer Component.

Create a custom component

File Path: src/components/CustomBlog/customBlog.js

import React from "react";

const CustomBlog = () => {
    const h1style = {
        textAlign: "center",
        margin: "1rem"
    };

    return (
        <h1 style={h1style}>Hello, this is custom blog.</h1>
    );
};

export default CustomBlog;
Import a custom component

File Path: src/components/CustomBlog/index.js

export {default} from './customBlog';
Add a custom component before Footer Component

File Path: src/targets/local-intercept.js

// Require TargetableReactComponent
const { Targetables } = require('@magento/pwa-buildpack');

module.exports = targets => {
    
    // Initialize TargetableReactComponent
    const targetables = Targetables.using(targets);

    // Create a TargetableReactComponent linked to the `main.js` file
    const MainComponenet = targetables.reactComponent(
        '@magento/venia-ui/lib/components/Main/main.js'
    );

    // Create a TargetableReactComponent linked to the `customBlog.js` file
    const CustomBlog = MainComponenet.addImport(
        "CustomBlog from 'ee-concept/src/components/CustomBlog/customBlog.js'"
    );

    // Insert a custom blog before Footer Component
    MainComponenet.insertBeforeJSX('<Footer />', `<${CustomBlog} />`);
};
Run the storefront
yarn watch:example
Output

We hope this blog may understandable and useful to you. You can email us at mage2developer@gmail.com if we missed anything or want to add any suggestions. We will respond to you as soon as possible. Happy to help 🙂