add newsletter to Magento PWA Studio
Magento PWA Studio: How to add a newsletter to the footer

Magento PWA Studio: How to add a newsletter to the footer

ced-pdf-title-image

Running short of time? Get PDF of the blog in your mail.

sharepost

With more and more traffic coming from mobile devices, the need for mobile-first solutions and PWAs have increased a great deal, along with different promotion techniques. Your business needs to have mobile-first solutions ready to stay in the game.Magento PWA studio will help you create an app that delivers a great user experience, is fast, works seamlessly, and is highly engaging. Learning how to add a newsletter in Magento PWA Studio is a much-needed skill for brand promotion and marketing.

Check out our Magento 2 PWA Theme For eCommerce, a fast and reliable solution.

check it out now

Using Magento PWA Studio, merchants can build PWAs that enhance user experience and redefine the shopper’s mobile experience.

At CedCommerce, we help merchants develop Progressive Web Apps that improve their overall performance and boost conversion rates. Being Adobe Bronze Solution Partner, we provide robust PWA solutions to clients that cater to their all-around business development needs.

Why add a newsletter in PWA Studio?

This blog focuses on adding the newsletter feature to the Venia footer in Magento PWA Studio, with a step to step guide.

Now, why is a newsletter a vital feature for PWA studio? It is an economical way of marketing your products and services. It also plays an essential role in promoting brand and product information. So learning how to add this feature to the Venia footer in Magento PWA Studio is something you should know.

Let’s get started!

How to add newsletter in PWA studio

Step 1:

The first step in how to add a newsletter in PWA Studio is to create a Venia project through scaffolding 

https://magento.github.io/pwa-studio/pwa-buildpack/scaffolding/

yarn create @magento/pwa

Once you have your scaffolded Venia project 

Then go inside your project directory 

First, we need to add our custom component for the newsletter in the Footer component For this, we need to add our code in 

local-intercept.js [YOUR_PROJECT_NAME/local-intercept.js]

local-intercept.js  is a default intercept file for the Venia project which is the default in the package.json file of your project. The intercept file describes the targets you want to intercept and define or extend. During build time, the framework looks for this file using the value for pwa-studio.targets.intercept in your project’s package.json file. These files execute after all the declared files register their Targets.

function localIntercept(targets) {
   const { Targetables } = require('@magento/pwa-buildpack');
   const targetables = Targetables.using(targets);
   
// Create a TargetableReactComponent linked to the `footer.js` file
   const FooterComponent = targetables.reactComponent(
       '@magento/venia-ui/lib/components/Footer/footer.js'
   );
// Add an import statement for Newsletter component
   const NewsLetter = FooterComponent.addImport(
       "NewsLetter from '/src/components/NewsLetter'"
   );
// Use targetable method to append newsletter component inside div of footer component
   FooterComponent.appendJSX(
       '<div className={classes.links}>',
       `<${NewsLetter}/>`
   );
}
module.exports = localIntercept;

STEP 2:

Then for the second step to add newsletter in PWA studio to Venia footer, we need to add our component inside src directory 

Click here to check out our PWA demo store

 

index.js [YOUR_PROJECT_NAME/src/components/NewsLetter/index.js]

import Newsletter from './newsletter.js';
export default Newsletter;

newsletter.js [YOUR_PROJECT_NAME/src/components/NewsLetter/newsletter.js]

import React, { Fragment, useEffect } from 'react';
import { Form } from 'informed';
import { FormattedMessage, useIntl } from 'react-intl';
import defaultClasses from './newsletter.css';
import FormError from '@magento/venia-ui/lib/components/FormError/formError';
import { isRequired } from '@magento/venia-ui/lib/util/formValidators';
import { mergeClasses } from '@magento/venia-ui/lib/classify';
import Button from '@magento/venia-ui/lib/components/Button';
import LoadingIndicator from '@magento/venia-ui/lib/components/LoadingIndicator';
import TextInput from '@magento/venia-ui/lib/components/TextInput';
import { useNewsletter } from 'src/peregrine/lib/talons/Newsletter/useNewsletter';
import { SUBSCRIBE_TO_NEWSLETTER } from './newsletter.gql';
import { useToasts } from '@magento/peregrine';
const Newsletter = props => {
   const { formatMessage } = useIntl();
   const classes = mergeClasses(defaultClasses, props.classes);
   const talonProps = useNewsletter({
       subscribeMutation: SUBSCRIBE_TO_NEWSLETTER
   });
   const [, { addToast }] = useToasts();
   const {
       errors,
       handleSubmit,
       isBusy,
       setFormApi,
       newsLetterResponse
   } = talonProps;
   useEffect(() => {
       if (newsLetterResponse && newsLetterResponse.status) {
           addToast({
               type: 'info',
               message: formatMessage({
                   id: 'newsletter.subscribeMessage',
                   defaultMessage: 'The email address is subscribed.'
               }),
               timeout: 5000
           });
       }
   }, [addToast, newsLetterResponse]);
   if (isBusy) {
       return (
           <div className={classes.modal_active}>
               <LoadingIndicator>
                   <FormattedMessage
                       id={'newsletter.loadingText'}
                       defaultMessage={'Subscribing'}
                   />
               </LoadingIndicator>
           </div>
       );
   }
   return (
       <Fragment>
           <div className={classes.root}>
               <h2 className={classes.title}>
                   <FormattedMessage
                       id={'newsletter.titleText'}
                       defaultMessage={'Subscribe to your Newsletter'}
                   />
               </h2>
               <FormError errors={Array.from(errors.values())} />
               <Form
                   getApi={setFormApi}
                   className={classes.form}
                   onSubmit={handleSubmit}
               >
                   <TextInput
                       autoComplete="email"
                       field="email"
                       validate={isRequired}
                   />
                   <div className={classes.buttonsContainer}>
                       <Button priority="high" type="submit">
                           <FormattedMessage
                               id={'newsletter.subscribeText'}
                               defaultMessage={'Subscribe'}
                           />
                       </Button>
                   </div>
               </Form>
           </div>
       </Fragment>
   );
};
export default Newsletter;


Click below to view our fast loading and an easy to use Cenia Pro Theme for Magento 2 PWA

check out the solution

STEP 3:

The third step to add a newsletter to PWA studio  is:

newsletter.css [YOUR_PROJECT_NAME/src/components/NewsLetter/newsletter.css]

.root {
   display: block;
   gap: 1.5rem;
   justify-items: stretch;
}
.form {
   display: grid;
   row-gap: 0.9375rem;
}
.modal {
   visibility: hidden;
   height: 100%;
   width: 100%;
   background-color: rgb(var(--venia-global-color-gray));
   text-align: center;
   position: absolute;
   bottom: 0;
}
.modal_active {
   visibility: visible;
   composes: modal;
   opacity: 0.9;
}
.buttonsContainer {
   display: grid;
   gap: 1.5rem;
   grid-auto-flow: row;
   justify-content: center;
   margin-top: 1rem;
   width: 100%;
}
.title {
   color: rgb(var(--venia-global-color-gray-900));
   font-size: var(--venia-typography-body-S-fontSize);
   font-weight: 600;
   margin-bottom: 20px;
   text-transform: capitalize;
}

Read our PWA success stories, something to motive you to build a PWA – The Roasters, Cloth Face Masks and EthnicSmart

STEP 4:

The final step to add a newsletter to Venia footer is:

Now we need to add Graphql Mutation for the newsletter which is available in Magento 2.4.2 version. You can check out this graphql here: https://devdocs.magento.com/guides/v2.4/graphql/mutations/subscribe-email-to-newsletter.html

Newsletter.gql.js [YOUR_PROJECT_NAME/src/components/NewsLetter/newsletter.gql.js]

import { gql } from '@apollo/client';
export const SUBSCRIBE_TO_NEWSLETTER = gql`
   mutation SubscribeToNewsletter($email: String!) {
       subscribeEmailToNewsletter(email: $email) {
           status
       }
   }
`;
export default {
   subscribeMutation: SUBSCRIBE_TO_NEWSLETTER
};

Now to complete the logic we will add a talon which will call the SubscribeToNewsletter mutation

useNewsletter.js [YOUR_PROJECT_NAME/src/peregrine/lib/talons/Newsletter/useNewsletter.js]

import { useCallback, useRef, useState, useMemo } from 'react';
import { useMutation } from '@apollo/client';
export const useNewsletter = props => {
   const { subscribeMutation } = props;
   const [subscribing, setSubscribing] = useState(false);
   const [subscribeNewsLetter, { error: newsLetterError, data }] = useMutation(
       subscribeMutation,
       {
           fetchPolicy: 'no-cache'
       }
   );
   const formApiRef = useRef(null);
   const setFormApi = useCallback(api => (formApiRef.current = api), []);
   const handleSubmit = useCallback(
       async ({ email }) => {
           setSubscribing(true);
           try {
               await subscribeNewsLetter({
                   variables: { email }
               });
           } catch (error) {
               if (process.env.NODE_ENV !== 'production') {
                   console.error(error);
               }
           }
           setSubscribing(false);
       },
       [subscribeNewsLetter]
   );
   const errors = useMemo(
       () => new Map([['subscribeMutation', newsLetterError]]),
       [newsLetterError]
   );
   return {
       errors,
       handleSubmit,
       isBusy: subscribing,
       setFormApi,
       newsLetterResponse: data && data.subscribeEmailToNewsletter
   };
};

After that run your project 

yarn build

yarn start

This is what the result should look like:

progressive web appsMobile

magento add newsletter footer

Desktop 

This is the procedure that you can follow for Magento PWA Studio to add a newsletter in the Venia footer. We hope we were able to share it in a simple way and would encourage you to give it a try.

You can expect similar articles as we want to share what we have learned, things that have made us what we are today.

Contact us for any related queries and we will be happy to help!

2
Leave a Reply