GithubHelp home page GithubHelp logo

revolunet / react-mailchimp-subscribe Goto Github PK

View Code? Open in Web Editor NEW
245.0 6.0 49.0 3.1 MB

React subscribe form for Mailchimp.

Home Page: https://revolunet.github.io/react-mailchimp-subscribe/

JavaScript 100.00%
reactjs mailchimp subscribe

react-mailchimp-subscribe's Introduction

react-mailchimp-subscribe

npm package

React subscribe form for Mailchimp.

Working demo : https://revolunet.github.io/react-mailchimp-subscribe/

Usage

Create a list on mailchimp, add a form and get its "action" attribute from the mailchimp UI

The MailchimpSubscribe gives you a render prop with a subscribe method that you can call with your data.

In your app :

import MailchimpSubscribe from "react-mailchimp-subscribe"

const url = "//xxxx.us13.list-manage.com/subscribe/post?u=zefzefzef&id=fnfgn";

// simplest form (only email)
const SimpleForm = () => <MailchimpSubscribe url={url}/>

// use the render prop and your custom form
const CustomForm = () => (
  <MailchimpSubscribe
    url={url}
    render={({ subscribe, status, message }) => (
      <div>
        <CustomForm onSubmitted={formData => subscribe(formData)} />
        {status === "sending" && <div style={{ color: "blue" }}>sending...</div>}
        {status === "error" && <div style={{ color: "red" }} dangerouslySetInnerHTML={{__html: message}}/>}
        {status === "success" && <div style={{ color: "green" }}>Subscribed !</div>}
      </div>
    )}
  />
)

see examples in ./demo/src

react-mailchimp-subscribe's People

Contributors

philipp-spiess avatar raffb avatar revolunet avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

react-mailchimp-subscribe's Issues

Add contact to a particular group list

Not sure if you can do this somehow in your package or it is a Pull request.

I would like to add the contact (who submitted the form) to be added to a custom group setup in mailchimp: https://mailchimp.com/help/automatically-add-subscribers-to-a-group-at-signup/

You would do this normally with the followoing line in your form:
<input type="hidden" name="group[611][64]" id="mce-group[611]-611-0" value="1">

Tried adding the following to the react component:
<input name="group[611][64]" id="mce-group[611]-611-0" defaultValue="1" />

But I take it I need to add these to the submit and onValidated, here is my entire code:

import React, { Component } from "react";
import NewsletterSignup from "react-mailchimp-subscribe";
 
// a basic form
const CustomForm = ({ status, message, onValidated }) => {
  let email, name;
  const submit = () =>
    email &&
    name &&
    email.value.indexOf("@") > -1 &&
    onValidated({
      EMAIL: email.value,
      NAME: name.value
    });

  return (
    <div
      style={{
        background: "#efefef",
        borderRadius: 2,
        padding: 10,
        display: "inline-block"
      }}
    >
      {status === "sending" && <div style={{ color: "blue" }}>sending...</div>}
      {status === "error" && (
        <div
          style={{ color: "red" }}
          dangerouslySetInnerHTML={{ __html: message }}
        />
      )}
      {status === "success" && (
        <div
          style={{ color: "green" }}
          dangerouslySetInnerHTML={{ __html: message }}
        />
      )}
      <input
        style={{ fontSize: "2em", padding: 5 }}
        ref={node => (name = node)}
        type="text"
        placeholder="Your name"
      />
      <br />
      <input
        style={{ fontSize: "2em", padding: 5 }}
        ref={node => (email = node)}
        type="email"
        placeholder="Your email"
      />
      <input name="group[611][64]" id="mce-group[611]-611-0" defaultValue="1" />
      <br />
      <button style={{ fontSize: "2em", padding: 5 }} onClick={submit}>
        Submit
      </button>
    </div>
  );
};

class Demo extends Component {
  render() {
    const url =
      "****";
    return (
      <div>
        <h1>react-mailchimp-subscribe Demo</h1>
        <h2>Default Form</h2>
        <NewsletterSignup url={url} />
        <h2>Custom Form</h2>
        <NewsletterSignup
          url={url}
          render={({ subscribe, status, message }) => (
            <CustomForm
              status={status}
              message={message}
              onValidated={formData => subscribe(formData)}
            />
          )}
        />
      </div>
    );
  }
}

export default Demo;

Firefox blocks JSONP request

Looks like Firefox's built-in content blocking does not like the request, or at least the implementation of the request.

screen shot 2019-01-23 at 12 34 55 pm

Demo CustomForm does not work on mobile

I'm using the demo's custom form and when testing it on mobile I realized that the customForm submit button isn't firing the onValidated event.

When I noticed the problem in my own code, I realized that the demo version also doesn't work on mobile either.

Is this a simple change or is there a complex issue with the demo that is breaking the validation?

Cannot add more fields

How do I add more fields to the submission?

I tried pretty much teh same thing to try and fill in an extra field but it doesn't work. Can anyone explain why? I made sure NAME is a field in my Mailchimp audience.

Any help much appreciated.

 <MailchimpSubscribe
  url={URL}
  render={({ subscribe, status, message }) =>  (
    <>
    <p class={`f3 fw6 mb4 ${status === 'success' && 'green'} ${status === 'error' && 'red'}`}>
      { message }
      </p>
    <form onSubmit={e => {
      e.preventDefault();
      const formData = {
        EMAIL: email,
        NAME: 'Example'
      };

      subscribe(formData);
      setName('')
  }}>
    <input type="email" placeholder='Your email'
    onChange={e => setName(e.target.value)} value={email}/>
    <button>Sign Me Up</button>
  </form>
  </>)}
  />

How to edit return of this in my project to add css classes and stuff.

I've managed to hack it together diting es/index.js return's render function for this.

Example code:
`
render() {
const { action, messages, className, style, styles } = this.props
const { status } = this.state
return React.createElement(
"div",
{ className: className, style: style },
React.createElement(
"form",
{ action: action, method: "post", noValidate: true },
React.createElement(
"div",
{ className: 'ui input', style: style },

      null,
      React.createElement("input", {
        ref: function ref(node) {
          return _this2.input = node;
        },
        type: "name",
        defaultValue: "",
        name: "NAME",
        required: true,
        placeholder: messages.namePlaceholder
      }),
      React.createElement("input", {
        ref: function ref(node) {
          return _this2.input = node;
        },
        type: "email",
        defaultValue: "",
        name: "EMAIL",
        required: true,
        placeholder: messages.inputPlaceholder
      }),

      React.createElement(
        "button",
        {
          className: 'ui primary button',
          role: 'button',
          attached: 'left',
          disabled: this.state.status === "sending" || this.state.status === "success",
          onClick: this.onSubmit,
          type: "submit"
        },
        messages.btnLabel
      )
    ),
    status === "sending" && React.createElement("p", { style: styles.sending, dangerouslySetInnerHTML: { __html: messages.sending } }),
    status === "success" && React.createElement("p", { style: styles.success, dangerouslySetInnerHTML: { __html: messages.success } }),
    status === "error" && React.createElement("p", { style: styles.error, dangerouslySetInnerHTML: { __html: messages.error } })
  )
);

};
`
How should I approach this if I want the code to live in my project, not the package, or is this something PR worthy?

Validation message

When you hit submit and user has both fields blank, is it possible to show a message?

something like this?

image

Tracking protection on Firefox for iOS blocks content

Only works when Tracking Protection is disabled.

When Tracking Protection is enabled I get a timeout. Works perfectly when Tracking Protection is disabled.

I can't access the console to see the exact error message.

same symptoms on tablet and phone:
iPad Air 2 — iOS 12, Firefox version 14.0
iPhone 6 – iOS 11.4.1, Firefox version 14.0

Firefox 64.0.2 for Mac works fine even when "Trackers" are being blocked

Mailchimp automated response formatting

Is there any way we can change the response error messages so there's no zero and hyphen?

e.g. '0 - The domain portion of the email address is invalid (the portion after the @: .com)'

Where are these messages coming from? How do we format them?

screen shot 2018-06-03 at 22 42 47

Fix cookie in request for future chrome versions

This is still not an issue, bit will be in future Chrome verisons. I get the following warning after I succesfully suscribe users to my newsletter:
A cookie associated with a cross-site resource at https://list-manage.com/ was set without the SameSite attribute. A future release of Chrome will only deliver cookies with cross-site requests if they are set with SameSite=None and Secure.

Allow extra fields via props

It would be great if we would be able to specify the fields we want to submit, not only email.
Think fields like name, company etc.

CORB blocked response on localhost

When I run your demo locally, it works great. When I copied my mailchimp web form URL to the project the request is now blocked.

Cross-Origin Read Blocking (CORB) blocked cross-origin response https://sohotokenlabs.us19.list-manage.com/subscribe?u=5ab64f1e30494af6c10c92f55&id=208b2b428b&EMAIL=email%40address.com&c=__jp0 with MIME type text/html. See https://www.chromestatus.com/feature/5629709824032768 for more details.

How do I style the form component

Please help. I've tried all I could to style the MailChimpSubscribe component but nothing is working.
I've used className to add a css class
<MailChimpSubscribe className="footer-form" />

I've also used style attribute
<MailChimpSubscribe style={{ color: "red" }} />

none of these seem to be working.

Reset form

There is some way to reset the form after return success?

CORS issue in next.js app

I'm trying to add this library to a next.js app, but when I send the request, I am getting a CORS error - Cross-Origin Read Blocking (CORB) blocked cross-origin response .... with MIME type text/html. See https://www.chromestatus.com/feature/5629709824032768 for more details.

Is there something in next.js needed to make this work? From the web, I might need to edit a next.config.js file, but I'm not really sure what to add to it if so. I presume someone has used this library with next.js, sorry if it is a question to ask them and not here.
https://nextjs.org/docs/api-reference/next.config.js/rewrites

Requests don't reflect on Mailchimp platform

Guys I don't know what's wrong the requests returns success all the time even if I send the same email address more than once and also the request type is GET am not sure if this is correct. any advice on that?

Subscribe to multiple lists possible?

I have a situation where I need to add the subscription to a second mailchimp list as well.

The sytnax only suggests one mailchimp list URL per form. Is there a way to subscribe to multiple lists at once?

Error receiving the JSONP result

I'm probably just as thick as a tar slushly here, and at this time I'm almost scared to ask, but I have no choice.

I'm developing a React app for a client and I've got two forms on a landing page. Just the email and the submit button. I'm using create-react-app and I've updated the start script in order to start the app with SSL by default: HTTPS=true react-scripts start.

Everything works flawlessly, apart from the Mailchimp form. I can embed it alright, style it, etc. – no problem, but when I send the form data I'm getting an error in Firefox:

Loading failed for the <script> with source “https://[account name].us17.list-manage.com/subscribe/post-json?u=[u id here]&id=[id here]&EMAIL=[url encoded email here]&c=__jp0”.

I don't know what this error is supposed to tell me exactly, but when I enter the URL in a browser I'm getting a pain text JSONP string back, so I guess the error message means that the browser can't deal with the result from Mailchimp.

The result that I get when I enter the URL in the browser, however, shows that requests are being processed by Mailchimp:

__jp0({"result":"success","msg":"Thank you for subscribing!"})

I'm at my wits end, so I'm grateful for any help here. What am I missing or doing wrong here?

React 16

Make it accept react 16 as dependency

onSubmitted not working with functions

Hi

I'm trying to redirect the user to a thank you page based on whether the status flag is "success" or not. Unf the status is unknown at the time of clicking the submit link/button so I can't add the path as so what I've thought of doing is adding onSubmitted on the rendered CustomForm and calling a simple function that will check the status and take the user to a different route (using react router history.push). The function isn't being hit at all though yet when I instead swap it out for a console.log it works.

<MailchimpSubscribe
      url={url}
      render={({ subscribe, status, message }) => (
      <>
       <CustomForm 
         status={status}
         message={message}
         onValidated={formData => subscribe(formData)}
         onSubmitted={back}
       />
    </>
)} />

const back = () => { history.push("/thank-you") };

Any ideas?

Cheers!

Refused to load script because it violates the following Content Security Policy directive

have a sample mailchimp form at http://eepurl.com/dzXHjD

used code from demo/src and i'm getting a CSP error.

modules.js?hash=d9603d8755a377c986c4df7e04101d8c1f8808b0:325448 Refused to load the script 'http://eepurl.com/dzXHjD&EMAIL=feaae%40HUi.com&NAME=feaea?c=__jp1' because it violates the following Content Security Policy directive: "script-src 'self' 'unsafe-inline' localhost:* http://unpkg.com https://unpkg.com http://cdn.jsdelivr.net https://cdn.jsdelivr.net http://.facebook.com https://.facebook.com http://.fbcdn.net https://.fbcdn.net http://connect.facebook.net https://connect.facebook.net http://.googleusercontent.com https://.googleusercontent.com http://.cdninstagram.com https://.cdninstagram.com http://assets.reactioncommerce.com https://assets.reactioncommerce.com http://cdnjs.cloudflare.com https://cdnjs.cloudflare.com http://fonts.googleapis.com https://fonts.googleapis.com http://fonts.gstatic.com https://fonts.gstatic.com http://enginex.kadira.io https://enginex.kadira.io http://.stripe.com https://.stripe.com 'unsafe-eval' http://www.paypal.com http://www.paypalobjects.com https://www.sandbox.paypal.com https://www.paypal.com https://www.paypalobjects.com https://tracking.qa.paypal.com https://akamai.mathtag.com".

what xxxx? before

what xxxx? before us13
action: '//xxxx.us13.list-manage.com/subscribe/post?u=695fze434a101fd2a718afddde8&id=72al97ece5'

Style the message on subscribe

I've figure out how to style inputs etc. but for the message no.
I've try multiple way to style the message, I've created a component instead a div with styled-components, CSS inline but nothing, I get the same message without the style that I want.
Any suggest?

Thanks

Error message includes html

When I get an error message it's including html. For example on duplicate email:

[email protected] is already subscribed to list INFURA News. <a href="https://infura.us14.list-manage.com/subscribe/send-email?e=cGF1bC5jaHJpc3RvcGhlNkBnbWFpbC5jb20%3D&u=7bec10aa5be97e80fcb0e7c52&id=13433031de">Click here to update your profile</a>

How are others handling this? In the demo it seems the error message is just being dropped in as a string.

Security?

Hi! I've seen from the network tab that we expose some sensible data, like list id and, probably, the apikey; is this really secure? Because from mailchimp docs they say that they api doesn't support unauthenticated client-side request. Thanks!

How to add a timeout value

My client is getting a Timeout error. I can't reproduce the error but I would like to try to add a timeout value of 2 seconds. Is this exposed as a property? If not how do I go into library to do it myself?

How to manipulate default value?

Tried < MailchimpSubscribe url={url} EMAIL={this.state.email} /> to retrieve a default value and then executed a function to automatically press the "submit" button. I failed.

Are there any props of < MailchimpSubscribe /> that I can pass in email data?

Automatically execute "Submit" button: autoSubmit = () => { < MailchimpSubscribe url={url} /> }
Is that the correct way to do it?

How do I apply styling

How do I apply material-ui styling to

<MailchimpSubscribe url={url}/>

I am only using email for subscription and my form is as follows

<form onSubmit={formData => subscribe(formData)}> <TextField variant="outlined" margin="normal" required type="email" fullWidth id="email" label="Email Address" name="EMAIL" autoComplete="email" autoFocus onChange={e => setEmail(e.target.value)} /> <Button type="submit" fullWidth variant="contained" color="primary" className={classes.submit} > Subscribe </Button> </form>

Working demo stuck on sending...

It seems that the module isn't working anymore. Was trying to implement in on my list, did everything but it keeps getting stuck on the "sending" message. Same behaviour observed in the working demo.

Enable reCAPTCHA

I've tried enabling reCAPTCHA for my list from MailChimp. When I do that and submit, the package returns an error saying "captcha".

Is there a way to include the reCAPTCHA from MailChimp in the form? Having a way limit bot submissions would be a useful feature.

Recipient "" has too many recent signup requests

Trying to use with Formik, with the code:

const url =
  'https://twosquarepixels.us20.list-manage.com/subscribe/post?u=69f211e10523fc65810fe216a&amp;id=cb44006301';

..

  <MailchimpSubscribe
            url={url}
            render={({ subscribe, status, message }) => (
               <Formik
                  onSubmit={values => {
                    console.log({ values }); // values: { email: "[email protected]" }
                    subscribe(values);
                  }}
                  initialValues={{ email: '' }}
                  render={() => {
                    return (
                      <Form id="mc-form">
                        <InputField>
                          <Field
                            name="email"
                            type="email"
                            className="control"
                            placeholder="Enter your email"
                            required="required"
                            id="mc-email"
                          />
                        </InputField>

                        <button type="submit">
                            Subscribe
                        </button>
                        <label className="mt10" htmlFor="mc-email" />
                      </Form>
                    );
                  }}
                />
               )}
          />

Getting this error:

Recipient "" has too many recent signup requests

Stuck on Sending

Demo and my own config are stuck on sending and eventually timeout no matter what.

[Proposal] Promise-based HOC wrapper for MailchimpSubscribe

I was recently tasked with implementing mailchimp subscription in react, but I found the implementation of MailchimpSubscrbe to be rather inconvenient for properly managing state.

The problem

In our case, we use react-google-recaptcha and react-final-form, but the problem is that final form expects that once we return from the onSubmit function, that the form has been submitted. Inside the onSubmit function, we wait for the recaptcha to complete, but when it comes to the subscribe callback exposed by MailchimpSubscribe, it does not return a promise; So calling that function inside the onSubmit function will immediately return which leads the form to assume the subscription was successful.

Solution

I came up with a higher-order component which simply exposes a function that returns a promise and you don't have to worry about status; Just wait for the function to complete and if there is an error at the end, you can "catch" that and do something with it. Here it is (hope you don't mind typescript 😄 ):

/* eslint-disable react-hooks/rules-of-hooks */
import React, { useCallback, useEffect, useRef } from "react";
import MailchimpSubscribe, { DefaultFormFields } from "react-mailchimp-subscribe";

interface MailchimpSubscribeHOCProps<MCF> {
    mailchimpSubscribe: (formFields: MCF) => Promise<void>;
}

/**
 * Wraps a component with the MailchimpSubscribe component and exposes a simple subscribe
 * function which returns a promise
 *
 * @param Wrapped The component to wrap
 * @param mailchimpSubscribeUrl The POST url used for subscribing via mailchimp
 * @returns A component which has the ability to subscribe to
 */
export default function withMailchimpSubscribe<T = {}, MCF = DefaultFormFields>(Wrapped: React.ComponentType<T & MailchimpHOCProps<MCF>>, mailchimpSubscribeUrl: string): React.FC<T> {
    const subscribeSuccess = useRef<() => void>(null);
    const subscribeError = useRef<(error?: any) => void>(null);

    useEffect(() => () => {
        // Avoid memory leaks(?) by removing any held references
        subscribeSuccess.current = null;
        subscribeError.current = null;
    }, []);

    // eslint-disable-next-line react-hooks/rules-of-hooks
    return useCallback((props: T) => (<MailchimpSubscribe<MCF>
        url={mailchimpSubscribeUrl}
        render={({ subscribe, status, message }) => {
            const mailchimpSubmit: (formFields: MCF) => Promise<void> = (formFields: MCF) => {
                subscribe(formFields);
                return new Promise<void>((resolve, reject) => {
                    subscribeSuccess.current = resolve;
                    subscribeError.current = reject;
                });
            };

            if (status === 'success' && subscribeSuccess.current != null) {
                subscribeSuccess.current();
            } else if (status === 'error' && subscribeError.current != null) {
                subscribeError.current(message);
            }
            return <Wrapped mailchimpSubscribe={mailchimpSubmit} {...props} />;
        }} />
        // eslint-disable-next-line react-hooks/exhaustive-deps
    ), [mailchimpSubscribeUrl]);
}

The promise resolves to nothing if the subscription was successful, otherwise it fails with an error message if the status is error.

Example

const mailchimpUrl = "...";
const MyCustomForm: React.FC = withMailchimpSubscribe(({ mailchimpSubscribe: subscribe }) => {
    // do some state management here

   return (
       <Form .../>
   );
}, mailchimpUrl);

Adding GDPR fields and a few examples

Hi. This was a very handy thing to plug in, I would have loved to see examples of adding more advanced fields though, maybe an expanded example. For instance I wanted to adopt GDPR early but couldn't quite figure out how to get the data sent. I ended up hacking in this:

onValidated({ EMAIL: email.value, FNAME: fname.value, LNAME: lname.value, GDPR: {[27]: gdpr.value} });

It triggers a warning though, any ideas how to do it in a better way? The bracket in the variable name was my main issue, they expect gdpr[27] for the GDPR email field.

Double opt-in

Hello,

thank you for this project, very quick and easy to implement. I was wondering if it is possible to enable double opt-in sign-ups, so that users are not immediately subscribed but receive an email to confirm their subscription instead.

I read here that it should be enough to mark the user's status as "pending" rather than "subscribed".

Callback regression

Looks like onSuccess and onError callbacks were added in 2.0.1, but not available in 2.1.0, is this due to the React version it depends on?

Compatibility with React 17

I just installed react-mailchimp-subscribe and got this error

npm ERR! Could not resolve dependency:
npm ERR! peer react@"15||16" from [email protected]
npm ERR! node_modules/react-mailchimp-subscribe
npm ERR! react-mailchimp-subscribe@"*" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.

I then installed with npm i react-mailchimp-subscribe --force

I have not tested yet if there are some issues.

But it would be nice if React 17 would be supported out of the box.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.