Skip to content

Instantly share code, notes, and snippets.

@manueltuero
Created November 4, 2019 19:33
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save manueltuero/f281a6603033c7679454a064bd9201cb to your computer and use it in GitHub Desktop.
Save manueltuero/f281a6603033c7679454a064bd9201cb to your computer and use it in GitHub Desktop.
A simple Form built with Gatsby and React Hooks to subscribe with Mailchimp
import React, { useState } from 'react';
import addToMailchimp from 'gatsby-plugin-mailchimp';
import styles from './styles.scss';
function SubscribeForm() {
const [email, setEmail] = useState('');
const [status, setStatus] = useState('');
const [message, setMessage] = useState('');
const handleSubmit = async event => {
event.preventDefault();
// Mailchimp always responds with status code 200, accompanied by a string indicating the result of the response.
const { result, msg } = await addToMailchimp(email);
result === 'success' && setEmail('');
// Removes the HTML returned in some response messages in case of error
setMessage(msg.split('<')[0]);
setStatus(result);
};
const handleChange = event => setEmail(event.target.value);
return (
<form className={styles.subscribeForm}>
<span className={styles.title}>Subscribe for latest updates</span>
<p className={styles.description}>
Sign Up for our newsletter and get notified when we publish new articles
for free!
</p>
<div className={styles.content}>
<input
className={styles.email}
type="email"
onChange={handleChange}
value={email}
placeholder="example@domain.com"
required
/>
<span
status={status}
className={
status === 'success' ? styles.messageSuccess : styles.messageFailure
}
>
{message}
</span>
</div>
<button className={styles.submitBtn} type="submit" onClick={handleSubmit}>
Subscribe
</button>
</form>
);
}
export default SubscribeForm;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment