PWA

Create a custom page with static route in Magento 2 PWA

There are many pages provided by PWA Venia Storefront like the Home page, Category page, Product page, Search page, etc. In many cases, we need to create custom pages.
Once you set up PWA Studio with Magento 2 and created a custom package, you should work in that custom package directory. So now we would get an idea of how to create a custom page by following steps, note that create all files inside packages/<custom_package>directory.

Step 1: Create a custom component
We need to create a custom component inside src/componentsdirectory, for example, DemoPage. So the file path would be src/components/DemoPage/demoPage.js

import React from "react";

const DemoPage = () => {
    const h1 = {
        textAlign: "center",
        margin: "1rem"
    }
    return (
        <h1 style={h1}>This is my custom page</h1>
    );
}

export default DemoPage;

Note: Inside the return() function we can return only one element, and if we want to add more than one element, we should wrap them in a single element. For example, this way:

return (
    <div>
        <strong>Name:</strong>
        <span>Daisy Paul</span>
    </div>
);

Step 2: Export custom component
We need to export a custom component inside the index.js file, the pattern of exporting is the same as the Venia UI package. The file path would be: src/components/DemoPage/index.js

export {default} from './demoPage';

Step 3: Add a static route
To add a static route, we need to create a local-intercept.js file and the file path would be src/targets/local-intercept.jsThis file is responsible for interacting with your plugins and components. The file name and its location is not compulsory as we used, it’s just an example. We prefer to follow the same pattern as the Venia UI package.

module.exports = targets => {
    targets.of("@magento/venia-ui").routes.tap(routes => {
        routes.push({
            name: "MyDemoPage",
            pattern: "/demopage",
            path: require.resolve("../components/DemoPage/demoPage.js")
        });
    });
};

Step 4: Register an intercept file
We need to register an intercept file inside our custom package’s package.json file, i.e. packages/<custom_package>/package.json.

Original:

"pwa-studio": {
    "targets": {
      "intercept": "./local-intercept.js"
    }
}

Replace with:

"pwa-studio": {
    "targets": {
      "intercept": "./src/targets/local-intercept"
    }
}

Step 5: Run custom package storefront
yarn watch:<custom_package>
i.e. yarn watch:example

Step 6: Navigate to a custom page
Open the storefront URL in the browser and navigate to ‘/demopage’ as shown in the following screenshot. For example, https://ee-concept-jbubv.local.pwadev:8422/demopage.

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 🙂