|
| 1 | +import { createRef, useState } from 'react'; |
| 2 | +import Image from 'next/image'; |
| 3 | +import { decode } from 'html-entities'; |
| 4 | +import ReCAPTCHA from 'react-google-recaptcha'; |
| 5 | +import Container from '@/components/containers/Container/Container'; |
| 6 | +import newsletterStyles from '@/styles/Newsletter.module.scss'; |
| 7 | +import SubmitButton from '@/components/buttons/SubmitButton/SubmitButton'; |
| 8 | +import S from './styles'; |
| 9 | + |
| 10 | +const SITE_KEY = process.env.NEXT_PUBLIC_RECAPTCHA_SITE_KEY; |
| 11 | + |
| 12 | +const NewsletterForm = ({ status, message, onValidated }) => { |
| 13 | + const [error, setError] = useState(null); |
| 14 | + const [name, setName] = useState(''); |
| 15 | + const [email, setEmail] = useState(''); |
| 16 | + const recaptchaRef = createRef(); |
| 17 | + |
| 18 | + const onReCAPTCHAChange = async captchaCode => { |
| 19 | + // If the reCAPTCHA code is null or undefined indicating that |
| 20 | + // the reCAPTCHA was expired then return early |
| 21 | + if (!captchaCode) { |
| 22 | + return; |
| 23 | + } |
| 24 | + try { |
| 25 | + const response = await fetch('/api/register', { |
| 26 | + method: 'POST', |
| 27 | + body: JSON.stringify({ email, name, captcha: captchaCode }), |
| 28 | + headers: { |
| 29 | + 'Content-Type': 'application/json', |
| 30 | + }, |
| 31 | + }); |
| 32 | + if (response.ok) { |
| 33 | + // If the response is ok than show the success console.log |
| 34 | + console.log('Email registered successfully'); |
| 35 | + } else { |
| 36 | + // Else throw an error with the message returned |
| 37 | + const error = await response.json(); |
| 38 | + throw new Error(error.message); |
| 39 | + } |
| 40 | + } catch (error) { |
| 41 | + console.log(error?.message || 'Something went wrong'); |
| 42 | + } finally { |
| 43 | + // Reset the reCAPTCHA when the request has failed or succeeded |
| 44 | + if (recaptchaRef?.current) { |
| 45 | + recaptchaRef.current.reset(); |
| 46 | + } |
| 47 | + |
| 48 | + setEmail(''); |
| 49 | + setName(''); |
| 50 | + } |
| 51 | + }; |
| 52 | + |
| 53 | + /** |
| 54 | + * Handle form submit. |
| 55 | + * |
| 56 | + * @return {{value}|*|boolean|null} |
| 57 | + */ |
| 58 | + const handleFormSubmit = event => { |
| 59 | + event.preventDefault(); |
| 60 | + |
| 61 | + setError(null); |
| 62 | + |
| 63 | + if (!name) { |
| 64 | + setError('Please enter a name'); |
| 65 | + return null; |
| 66 | + } |
| 67 | + |
| 68 | + if (!email) { |
| 69 | + setError('Please enter a valid email address'); |
| 70 | + return null; |
| 71 | + } |
| 72 | + |
| 73 | + recaptchaRef.current.execute(); |
| 74 | + |
| 75 | + const isFormValidated = onValidated({ EMAIL: email }); |
| 76 | + |
| 77 | + event.target.reset(); |
| 78 | + |
| 79 | + // On success return true |
| 80 | + return name && email && email.indexOf('@') > -1 && isFormValidated; |
| 81 | + }; |
| 82 | + |
| 83 | + /** |
| 84 | + * Handle Input Key Event. |
| 85 | + * |
| 86 | + * @param event |
| 87 | + */ |
| 88 | + const handleInputKeyEvent = event => { |
| 89 | + setError(null); |
| 90 | + // Number 13 is the "Enter" key on the keyboard |
| 91 | + if (event.keyCode === 13) { |
| 92 | + // Cancel the default action, if needed |
| 93 | + event.preventDefault(); |
| 94 | + // Trigger the button element with a click |
| 95 | + handleFormSubmit(); |
| 96 | + } |
| 97 | + }; |
| 98 | + |
| 99 | + /** |
| 100 | + * Extract message from string. |
| 101 | + * |
| 102 | + * @param {String} message |
| 103 | + * @return {null|*} |
| 104 | + */ |
| 105 | + const getMessage = message => { |
| 106 | + if (!message) { |
| 107 | + return null; |
| 108 | + } |
| 109 | + const result = message?.split('-') ?? null; |
| 110 | + if ('0' !== result?.[0]?.trim()) { |
| 111 | + return decode(message); |
| 112 | + } |
| 113 | + const formattedMessage = result?.[1]?.trim() ?? null; |
| 114 | + return formattedMessage ? decode(formattedMessage) : null; |
| 115 | + }; |
| 116 | + |
| 117 | + return ( |
| 118 | + <section className={newsletterStyles.newsletter}> |
| 119 | + <Container customClass={newsletterStyles.newsletter__inner}> |
| 120 | + <h2 className={newsletterStyles.newsletter__title}> |
| 121 | + Sign up for news |
| 122 | + <span className={newsletterStyles.newsletter__right_chevron}> |
| 123 | + <Image |
| 124 | + src='/images/svg/right-chevron.svg' |
| 125 | + height={18} |
| 126 | + width={18} |
| 127 | + alt='Right Chevron SVG' |
| 128 | + /> |
| 129 | + </span> |
| 130 | + </h2> |
| 131 | + <div> |
| 132 | + <form |
| 133 | + className={newsletterStyles.newsletter__form} |
| 134 | + onSubmit={handleFormSubmit} |
| 135 | + > |
| 136 | + <input |
| 137 | + className={`${newsletterStyles.newsletter__input} ${newsletterStyles.newsletter__name}`} |
| 138 | + onChange={event => setName(event?.target?.value ?? '')} |
| 139 | + type='text' |
| 140 | + name='name' |
| 141 | + value={name} |
| 142 | + placeholder='name' |
| 143 | + /> |
| 144 | + <input |
| 145 | + className={`${newsletterStyles.newsletter__input} ${newsletterStyles.newsletter__email}`} |
| 146 | + onChange={event => setEmail(event?.target?.value ?? '')} |
| 147 | + type='email' |
| 148 | + name='email' |
| 149 | + value={email} |
| 150 | + placeholder='email' |
| 151 | + onKeyUp={event => handleInputKeyEvent(event)} |
| 152 | + /> |
| 153 | + <SubmitButton label='Subscribe' $buttonType='newsletter__button' /> |
| 154 | + |
| 155 | + <ReCAPTCHA |
| 156 | + ref={recaptchaRef} |
| 157 | + size='invisible' |
| 158 | + sitekey={SITE_KEY} |
| 159 | + onChange={onReCAPTCHAChange} |
| 160 | + /> |
| 161 | + </form> |
| 162 | + |
| 163 | + <div className={newsletterStyles.newsletterFormInfo}> |
| 164 | + {status === 'sending' && ( |
| 165 | + <div className={newsletterStyles.newsletterFormSending}> |
| 166 | + Sending... |
| 167 | + </div> |
| 168 | + )} |
| 169 | + {status === 'error' || error ? ( |
| 170 | + <div |
| 171 | + className={newsletterStyles.newsletterFormError} |
| 172 | + dangerouslySetInnerHTML={{ |
| 173 | + __html: error || getMessage(message), |
| 174 | + }} |
| 175 | + /> |
| 176 | + ) : null} |
| 177 | + {status === 'success' && status !== 'error' && !error && ( |
| 178 | + <div |
| 179 | + className={newsletterStyles.newsletterFormSuccess} |
| 180 | + dangerouslySetInnerHTML={{ __html: decode(message) }} |
| 181 | + /> |
| 182 | + )} |
| 183 | + </div> |
| 184 | + </div> |
| 185 | + </Container> |
| 186 | + </section> |
| 187 | + ); |
| 188 | +}; |
| 189 | + |
| 190 | +export default NewsletterForm; |
0 commit comments