How To Build a Mailchimp Form with React

    Learn how build a React form to create subscribers in your Mailchimp account.

    1Prepare your project

    Install the React helper library in your project:

    npm install @statickit/react

    Then add the StaticKitProvider to your top-level app component. For example, if you are using Next.js, here's what your pages/_app.js file might look like:

    import { StaticKitProvider } from '@statickit/react';
    function App({ Component, pageProps }) {
    return (
    <StaticKitProvider site="{your-site-id}">
    <Component {...pageProps} />
    </StaticKitProvider>
    );
    }
    export default App;

    2Configure your function

    In your statickit.json file, add a Mailchimp function:

    {
    "functions": {
    "addToMailchimp": {
    "app": "mailchimp",
    "type": "addOrUpdateListMember"
    }
    }
    }

    Then, deploy your changes to StaticKit:

    statickit deploy -k <your-deploy-key>

    You'll be prompted with instructions on how to save your Mailchimp API key and audience.

    3Build your form

    Here's an example component that calls your addToMailchimp function in the form submit handler.

    import React, { useState } from 'react';
    import { useStaticKit, ValidationError } from '@statickit/react';
    import { addToMailchimp } from '@statickit/functions';
    function OptInForm(props) {
    const client = useStaticKit();
    const [emailAddress, setEmailAddress] = useState('');
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [isSubmitted, setIsSubmitted] = useState(false);
    const [errors, setErrors] = useState([]);
    const handleSubmit = async e => {
    e.preventDefault();
    setErrors([]);
    setIsSubmitting(true);
    let resp = await addToMailchimp(client, { emailAddress });
    switch (resp.status) {
    case 'ok':
    setIsSubmitted(true);
    break;
    case 'argumentError':
    setErrors(resp.errors);
    setIsSubmitting(false);
    break;
    default:
    setIsSubmitting(false);
    break;
    }
    }
    if (isSubmitted) {
    return <p>Thanks for joining!</p>;
    }
    return (
    <form onSubmit={handleSubmit}>
    <label htmlFor="email">
    Email Address
    </label>
    <input
    id="email"
    type="email"
    name="email"
    onChange={e => setEmailAddress(e.target.value)}
    value={emailAddress}
    />
    <ValidationError
    prefix="Email"
    field="emailAddress"
    errors={errors}
    />
    <button type="submit" disabled={isSubmitting}>
    Sign Up
    </button>
    </form>
    );
    }

    Here we are only passing an emailAddress to Mailchimp. You can optionally pass along mergeFields as well:

    let resp = await addToMailchimp(client, {
    emailAddress,
    mergeFields: {
    FNAME: firstName,
    LNAME: lastName
    }
    });

    Get the full source code →


    Check out the Mailchimp reference to see all available function types.