jonbio/components/FormSubscribe.js

73 lines
2.3 KiB
JavaScript
Raw Normal View History

2021-08-18 17:33:15 +02:00
import { useRef, useState } from 'react'
import siteMetadata from '@/data/siteMetadata'
2021-09-02 10:17:34 +02:00
const FormSubscribe = () => {
2021-08-18 17:33:15 +02:00
const inputEl = useRef(null)
const [message, setMessage] = useState('')
2021-09-02 10:17:34 +02:00
const [subscribed, setSubscribed] = useState(false)
2021-08-18 17:33:15 +02:00
const subscribe = async (e) => {
e.preventDefault()
const res = await fetch(`/api/${siteMetadata.newsletter.provider}`, {
body: JSON.stringify({
email: inputEl.current.value,
}),
headers: {
'Content-Type': 'application/json',
},
method: 'POST',
})
const { error } = await res.json()
if (error) {
2021-09-02 10:17:34 +02:00
setMessage('Your e-mail adress is invalid or you are already subscribed!')
2021-08-18 17:33:15 +02:00
return
}
inputEl.current.value = ''
2021-09-02 10:17:34 +02:00
setSubscribed(true)
2021-08-18 17:33:15 +02:00
setMessage('Successfully! 🎉 You are now subscribed.')
}
return (
<div>
<div className="pb-1 text-lg font-semibold text-gray-800 dark:text-gray-100">
Subscribe to the newsletter
</div>
<form className="flex flex-col sm:flex-row" onSubmit={subscribe}>
2021-08-18 17:33:15 +02:00
<div>
<label className="sr-only" htmlFor="email-input">
Email address
</label>
<input
autoComplete="email"
className="px-4 py-2 placeholder-gray-500 bg-white border rounded-md appearance-none w-72 border-neutrals-cool-grey-300 text-neutrals-cool-grey-900 dark:bg-black focus:outline-none focus:ring-primary-400 dark:focus:border-primary-600"
2021-08-18 17:33:15 +02:00
id="email-input"
name="email"
2021-09-10 14:32:18 +02:00
placeholder={subscribed ? "You're subscribed ! 🎉" : 'Enter your email'}
2021-08-18 17:33:15 +02:00
ref={inputEl}
required
type="email"
2021-09-02 10:17:34 +02:00
disabled={subscribed}
2021-08-18 17:33:15 +02:00
/>
</div>
<div className="flex w-full mt-2 rounded-md shadow-sm sm:mt-0 sm:ml-3">
2021-08-18 17:33:15 +02:00
<button
className={`w-full bg-primary-500 dark:bg-primary-500 px-4 py-2 border border-transparent rounded-md font-medium text-white ${
subscribed ? 'cursor-default' : 'hover:bg-primary-700 dark:hover:bg-primary-400'
} focus:outline-none focus:ring-2 focus:ring-offset-2 focus:primary-700`}
2021-08-18 17:33:15 +02:00
type="submit"
2021-09-02 10:17:34 +02:00
disabled={subscribed}
2021-08-18 17:33:15 +02:00
>
2021-09-02 10:17:34 +02:00
{subscribed ? 'Thank you!' : 'Sign up'}
2021-08-18 17:33:15 +02:00
</button>
</div>
</form>
</div>
)
}
2021-09-02 10:17:34 +02:00
export { FormSubscribe }