PWA

Create a static route with URL params in Magento 2 PWA

Magento 2 PWA Studio provides a built-in Venia UI package which is very useful to reference when customizing a storefront. In many cases, we need to create a static route with URL params like a search page. Let’s get an idea of how to create a custom page having a static route with URL params.

Step 1: Create a custom component
File Path: src/components/DemoParams/demoParams.js

import React from "react";
import { useParams } from "react-router-dom";

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

    const { pagenum = "first"} = useParams();

    return (
        <h1 style={h1}>This is my {pagenum} page</h1>
    );
}

export default DemoParams;

Step 2: Export custom component
File Path: src/components/DemoParams/index.js

export {default} from './demoParams';

Step 3: Add a static route
File Path: src/targets/local-intercept.js

module.exports = targets => {
    targets.of("@magento/venia-ui").routes.tap(routes => {
        routes.push({
            name: "MyDemoPageParams",
            pattern: "/demoparams/:pagenum?",
            path: require.resolve("../components/DemoParams/demoParams.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 browser and navigate to ‘/demoparams/second’ as shown in the following screenshot.
For example, https://ee-concept-jbubv.local.pwadev:8422/demoparams/second.

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 🙂