Adding Mailchimp Subscribe Newsletter in Next.js React Application.
In this blog we will learn about how to add a mailchimp newsletter subscription in a Nextjs react application.
Get the Mailchimp URL
Create an account on Mailchimp if you don’t already have one.
Create an audience campaign.
Navigate to Campaigns > Signup Forms > Signup forms tab and click on Embed forms
and then select.
Copy the the form action value
// Example.
<form action="https://xyz.us19.list-manage.com/subscribe/post?u=96386247a54fss21f7bb3a1c&id=072ss2cbd"...
Create Environment variable in Next.js app
Add Env variable in next.js application .env
file for Mailchimp URL and paste the URL taken from form action above.
NEXT_PUBLIC_MAILCHIMP_URL=https://xyz.us19.list-manage.com/subscribe/post?u=96386247a54fss21f7bb3a1c&id=072ss2cbd
Install the React Mailchimp Subscribe Package
npm i react-mailchimp-subscribe html-entities
Create a React Component in next.js called NewsletterForm
Notice we have added NewsletterForm
component which we will add shortly.
import MailchimpSubscribe from 'react-mailchimp-subscribe';
import NewsletterForm from './NewsletterForm';
const NewsletterSubscribe = () => {
const MAILCHIMP_URL = process.env.NEXT_PUBLIC_MAILCHIMP_URL;
return (
<MailchimpSubscribe
url={ MAILCHIMP_URL }
render={ ( props ) => {
const { subscribe, status, message } = props || {};
return (
<NewsletterForm
status={ status }
message={ message }
onValidated={ formData => subscribe( formData ) }
/>
);
} }
/>
);
};
export default NewsletterSubscribe;
Create another component called NewsletterForm
import { useState } from 'react';
import { decode } from 'html-entities';
const NewsletterForm = ( { status, message, onValidated }) => {
const [ error, setError ] = useState(null);
const [ email, setEmail ] = useState(null);
/**
* Handle form submit.
*
* @return {{value}|*|boolean|null}
*/
const handleFormSubmit = () => {
setError(null);
if ( ! email ) {
setError( 'Please enter a valid email address' );
return null;
}
const isFormValidated = onValidated({ EMAIL: email });
// On success return true
return email && email.indexOf("@") > -1 && isFormValidated;
}
/**
* Handle Input Key Event.
*
* @param event
*/
const handleInputKeyEvent = ( event ) => {
setError(null);
// Number 13 is the "Enter" key on the keyboard
if (event.keyCode === 13) {
// Cancel the default action, if needed
event.preventDefault();
// Trigger the button element with a click
handleFormSubmit();
}
}
/**
* Extract message from string.
*
* @param {String} message
* @return {null|*}
*/
const getMessage = (message) => {
if ( !message ) {
return null;
}
const result = message?.split('-') ?? null;
if ( "0" !== result?.[0]?.trim() ) {
return decode(message);
}
const formattedMessage = result?.[1]?.trim() ?? null;
return formattedMessage ? decode( formattedMessage ) : null;
}
return (
<>
<div className="d-flex newsletter-input-fields">
<div className="mc-field-group">
<input
onChange={(event) => setEmail(event?.target?.value ?? '')}
type="email"
placeholder="Your email"
className="mr-2"
onKeyUp={(event) => handleInputKeyEvent(event)}
/>
</div>
<div className="button-wrap wp-block-button">
<button className="wp-block-button__link" onClick={handleFormSubmit}>
Submit
</button>
</div>
</div>
<div className="newsletter-form-info">
{status === "sending" && <div>Sending...</div>}
{status === "error" || error ? (
<div
className="newsletter-form-error"
dangerouslySetInnerHTML={{ __html: error || getMessage( message ) }}
/>
) : null }
{status === "success" && status !== "error" && !error && (
<div dangerouslySetInnerHTML={{ __html: decode(message) }} />
)}
</div>
</>
);
}
export default NewsletterForm
This will create a Newsletter Form in your React Application go ahead and try it out
That’s all folks!