Custom mailchimp signup form in React Custom mailchimp signup form in React ajax ajax

Custom mailchimp signup form in React


It is possible. [1]

As you mentioned in your link, MailChimp allows you to post the values of form elements on our client to subscribe people to your mailing list. Anything more advanced than that, and you need to use their API, thus requiring CORS (i.e. the API can't be utilized by the client).

If you aren't using React – you can simply copy/paste MailChimp's embedded form builder. But if you are in React, here's what you can do:

1) Get the u and id value

This is outlined in the link above. Or, You can go into your form builder and find the action field: it will be something like https://cool.us16.list-manage.com/subscribe/post?u=eb05e4f830c2a04be30171b01&id=8281a64779 where u and id are in the query arguments.

2) Add onChange and value attributes to form elements

If you just have some simple form elements, you'll notice that typing doesn't do anything. Typing doesn't render any text inside the input elements. Read https://reactjs.org/docs/forms.html to understand why. (React needs a single source of truth for state).

The value needs to be updated. You can do this by updating state in a function that's bind'd.

<input   value={this.state.emailValue}   onChange={ (e)=>{this.setState({emailValue: e.target.value});} } /> 

3) Bonus: include MailChimp's antispam fields

If you read the code inside the embedded forms, you'll notice things like:

<!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups--><div style="position: absolute; left: -5000px;" aria-hidden="true"><input type="text" name="b_eb05e4f830c2a04be30171b01_8281a64779" tabindex="-1" value=""></div><div class="clear"><input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button"></div>

You can include these in React by changing the appropriate fields for Babel and JSX. class needs to be className. the <input> tag needs to be closed, and style needs to be passed as an object.

In sum: here's an entire component

import React from 'react'class SubscribePage extends React.Component {  constructor(props) {    super(props);    this.state = {        emailValue: '',        fNameValue: '',        lNameValue: '',    };  }    render() {        return (                <form action="https://cool.us16.list-manage.com/subscribe/post" method="POST" noValidate>                  <input type="hidden" name="u" value="eb05e4f830c2a04be30171b01"/>                <input type="hidden" name="id" value="8281a64779"/>                <label htmlFor='MERGE0'>                    Email                    <input                         type="email"                         name="EMAIL"                         id="MERGE0"                        value={this.state.emailValue}                         onChange={ (e)=>{this.setState({emailValue: e.target.value});} }                         autoCapitalize="off"                         autoCorrect="off"                     />                 </label>                <label htmlFor='MERGE1'>                    First name                    <input                         type="text"                         name="FNAME"                         id="MERGE1"                         value={this.state.fNameValue}                         onChange={(e)=>{this.setState({fNameValue: e.target.value});}}                    />                </label>                <label htmlFor='MERGE2'>                    Last name                    <input                         type="text"                         name="LNAME"                         id="MERGE2"                         value={this.state.lNameValue}                         onChange={(e)=>{this.setState({lNameValue: e.target.value});}}                    />                </label>                  <input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" className="button"/>                <div style={{position: 'absolute', left: '-5000px'}} aria-hidden='true' aria-label="Please leave the following three fields empty">                    <label htmlFor="b_name">Name: </label>                    <input type="text" name="b_name" tabIndex="-1" value="" placeholder="Freddie" id="b_name"/>                    <label htmlFor="b_email">Email: </label>                    <input type="email" name="b_email" tabIndex="-1" value="" placeholder="youremail@gmail.com" id="b_email"/>                    <label htmlFor="b_comment">Comment: </label>                    <textarea name="b_comment" tabIndex="-1" placeholder="Please comment" id="b_comment"></textarea>                </div>              </form>        )    }}export default SubscribePage

[1]: Note that the user will be taken to a MailChimp page, and asked to verify the subscription by clicking on a link in their email. To avoid this, you gotta use the API


I ran into a lot of issues trying to get the form to work in React and not open a confirmation page.

There are a few ways to get around this, the easiest method is to use the react-mailchimp-subscribe package. This is super strait forward and the package is fairly light. The only thing needed to get this form to work is the action URL that Mailchimp provides you on the Embed Form page for your list.

If you don't want to use the package, you can dive into the source and recreate what is being done very simply. The few things that have to be changed are the URL from

http://xxxxx.us#.list.com/subscribe/post?u=xxxxx&id=xxxx

to

http://xxxxx.us#.list.com/subscribe/post-json?u=xxxxx&id=xxxx

In addition to adding the -json, you will need to add param c that is blank (this can be done in the jsonp request or added to the url by adding &c=?).

With this implementation you should no longer get redirected and all messages will come back in JSON format. Also note that you do not need to have their script tag on your page for this to work.

References:

  1. AJAX Mailchimp signup form integration


If someone is looking for a ready to use React solution (credit to @adriendenat in this answer):

import jsonp from 'jsonp';import queryString from 'query-string';// ...const subscribeToNewsLetter = () => {  const formData = {    EMAIL: // your email string,  };  jsonp(`YOUR_URL/subscribe/post-json?u=YOUR_U&id=YOUR_ID&${queryString.stringify(formData)}`, { param: 'c' }, (err, data) => {    console.log('err:', err);    console.log('data:', data);  });}