Learn how build a React form to create subscribers in your Mailchimp account.
1. Prepare your project
Install the React helper library in your project:
npm install @formspree/react
Then add the FormspreeProvider
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 { FormspreeProvider } from '@formspree/react';
function App({ Component, pageProps }) {
return (
<FormspreeProvider project="{your-project-id}">
<Component {...pageProps} />
</FormspreeProvider>
);
}
export default App;
2. Configure your form
In your formspree.json
file, add an opt-in form.
{
"forms": {
"optInForm": {
"name": "Opt-In Form",
"actions": [{
"app": "mailchimp",
"type": "addOrUpdateContact",
"audience": "8djs8fg8d",
"apiKey": "$MAILCHIMP_APIKEY"
}]
}
}
}
Then, deploy your changes to Formspree:
formspree deploy -k <your-deploy-key>
Learn more about Mailchimp actions →
3. Build your form
Wire up your form component using the useForm
hook:
import React from 'react';
import { useForm, ValidationError } from '@formspree/react';
function OptInForm() {
const [state, handleSubmit] = useForm("optInForm");
if (state.succeeded) {
return <p>Thanks for joining!</p>;
}
return (
<form onSubmit={handleSubmit}>
<label htmlFor="email">
Email Address
</label>
<input
id="email"
type="email"
name="email"
/>
<ValidationError
prefix="Email"
field="email"
errors={state.errors}
/>
<button type="submit" disabled={state.submitting}>
Sign Up
</button>
</form>
);
}
export default OptInForm;
Learn more about the Formspree CLI →
Learn more about Formspree and React →