In this tutorial, Today I will explain to how to create custom router in Magento 2 PWA. If you created some custom module in PWA and then, you want to add custom router, for that you need to create custom router.
You may also like this :
Let’s follow some below steps for that.
- Magento root directory = {baseUrl} = /var/www/html/m242
1) First, you need to create this folder {baseUrl}/pwa-studio/packages/venia-concept/src/components/Helloworld and then, create helloworld.js file at {baseUrl}/pwa-studio/packages/venia-concept/src/components/Helloworld/ and paste the below code which you want to set in custom router :
/**
* Created By : Rohan Hapani
*/
import React from "react";
import { useParams } from "react-router-dom";
const customStyles = {
textAlign: "center",
margin: "1rem",
fontSize: "2rem"
};
const Helloworld = () => {
return (
<div>
<h1 style={customStyles}>Welcome to Magento 2 PWA venia theme!</h1>
</div>
);
}
export default Helloworld;
2) Now, Create index.js file at {baseUrl}/pwa-studio/packages/venia-concept/src/components/Helloworld/ and paste the below code for export Helloworld component :
/**
* Created By : Rohan Hapani
*/
/* src/components/Helloworld/index.js */
export {default} from './helloworld';
3) Then, Create local-intercept.js file at {baseUrl}/pwa-studio/packages/venia-concept/src/targets/ and paste the below code for plugin interacts with framework.
/**
* Created By : Rohan Hapani
*/
module.exports = targets => {
targets.of("@magento/venia-ui").routes.tap(routes => {
routes.push({
name: "HelloworldCustomRouter",
pattern: "/helloworld",
path: require.resolve("../components/Helloworld/helloworld.js")
});
return routes;
});
};
4) In Last, Update your package.json file at {baseUrl}/pwa-studio/packages/venia-concept/ and paste the below code in the end of file to update local-intercept file path :
"pwa-studio": {
"targets": {
"intercept": "src/targets/local-intercept"
}
}
That’s it !!!
Now, you need to execute yarn using below command :
yarn run watch:venia
and execute this url : http://0.0.0.0:10000/helloworld
You need to check your url after complete yarn command and then, add helloworld action in your browser.
Output :
I hope this blog is easy to understand about how to create custom router in Magento 2 PWA. In case, I missed anything or need to add some information, always feel free to leave a comment in this blog, I’ll get back with proper solution.
Keep liking and sharing !!