PWA

How to create a React hook in Magento 2 PWA

Hooks allow us to create function components that are used to reuse the same feature in more than one class component. There are many built-in React hooks defined in Venia and Peregrine libraries. We can use React hooks for the state management feature, to set data and to retrieve data.

In this blog, we get an idea of how we can create a custom hook and render it in our class component. Let’s take the example of adding a custom link in the header. When clicking on that link, the navigation menu would be toggled the same as the main menu toggled in mobile view.

Create a hook

First, we create a hook for handling a state of navigation menu toggle. We create a callback function component named handleOpenNavigation which returns the state of the nav menu. Currently, we are returning a single function component, you can return more than one function component separated by a comma. For example, return {funcName1, funcName2, funcName3};
File Path: packages/example-concept/src/components/CustomMenuLink/useMenuLink.js

import {useCallback} from 'react';
import {useAppContext} from "@magento/peregrine/lib/context/app";

export const useMenuLink = () => {
    const [, {toggleDrawer}] = useAppContext();

    const handleOpenNavigation = useCallback(() => {
        toggleDrawer('nav');
    }, [toggleDrawer]);

    return {
        handleOpenNavigation
    };
}
Create a component file

We create a component for adding a custom link in the header. We render a hook and call it on onclick event of a custom link. Note that, you should use the same constant name as you returned in the hook.
File Path: packages/example-concept/src/components/CustomMenuLink/menuLink.js

import React from 'react';
import {FormattedMessage} from 'react-intl';
import {useMenuLink} from "./useMenuLink";

const MenuLink = () => {
    const {handleOpenNavigation} = useMenuLink();

    return (
        <button onClick={handleOpenNavigation}>
            <FormattedMessage id={'demoLink'} defaultMessage={'Demo Link'}/>
        </button>
    );
};

export default MenuLink;
Render a component

To render a Custom MenuLink component create an index.js file and add the following code:
File Path: packages/example-concept/src/components/CustomMenuLink/index.js

export {default} from './menuLink';
Add a component to the header

Now we add our CustomMenuLink component to Header React component using insertAfterJSX function of the TargetableReactComponent class.
File Path: packages/example-concept/src/targets/local-intercept.js

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

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

    const HeaderComponent = targetables.reactComponent(
        '@magento/venia-ui/lib/components/Header/header.js'
    );

    const CustomMenuLink = HeaderComponent.addImport(
        "MenuLink from 'example-concept/src/components/CustomMenuLink'"
    );

    HeaderComponent.insertAfterJSX('<MegaMenu />', `<${CustomMenuLink} />`);
};
Run PWA storefront

Execute the following command in the terminal to build and watch your example package:

yarn watch:example

Open the storefront URL and you can see the custom link named as Demo Link like the following screenshot. When you click on that link, the navigation menu would be opened.

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 🙂