Custom mailchimp signup form in React

前端 未结 4 1653
后悔当初
后悔当初 2021-02-05 09:54

I have a react app that I would like to add mailchimp signup form to. I am building a custom signup form and have user sign up by entering their first and last name and email. I

相关标签:
4条回答
  • 2021-02-05 10:12

    Like @marco-gaspari, I also ran into a lot of issues with this. My answer is a variation of theirs, but with some tweaks that, for me, were necessary to make it work.

    In addition to switching postat the end of the action url to post-json and including the c attribute equal to ? (in addition to the u and id attributes from the original url; all of which I chose to incorporate as hidden input fields), I also had to redirect the output to a hidden <iframe>. Otherwise, a new page opened with the json response.

    This may have been due to my using a custom form; but for others also using custom Mailchimp signup forms, this solution may be helpful.

    <form action="https://xxx.usxx.list-manage.com/subscribe/post-json" method="post" className="validate" target="hiddenFrame" >
           <!--u and id values from url generated by Mailchimp form builder -->
           <input type="hidden" name="u" value="xxxxxxxx" />
           <input type="hidden" name="id" value="xxxxxxx" />
           <input type="hidden" name="c" value="?" />
     </form>
        <iframe name="hiddenFrame" src="about:blank" style={{display:'none'}}></iframe>
    
    
    0 讨论(0)
  • 2021-02-05 10:22

    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&amp;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

    0 讨论(0)
  • 2021-02-05 10:30

    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
    0 讨论(0)
  • 2021-02-05 10:36

    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&amp;id=YOUR_ID&${queryString.stringify(formData)}`, { param: 'c' }, (err, data) => {
        console.log('err:', err);
        console.log('data:', data);
      });
    }
    
    0 讨论(0)
提交回复
热议问题