-
Notifications
You must be signed in to change notification settings - Fork 1
/
contact-form.js
105 lines (94 loc) · 2.59 KB
/
contact-form.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import styled from "@emotion/styled"
import { Form, Formik } from "formik"
import React, { useState } from "react"
import { MdSend } from "react-icons/md"
import * as yup from "yup"
import { rhythm } from "../utils/typography"
import { Button } from "./basic"
import { ErrorAlert } from "./form/error-alert"
import { Field } from "./form/field"
const validationSchema = yup.object({
name: yup.string().required(),
email: yup
.string()
.email()
.required(),
message: yup.string().required(),
})
const encode = data => {
return Object.keys(data)
.map(key => encodeURIComponent(key) + "=" + encodeURIComponent(data[key]))
.join("&")
}
const StyledForm = styled(Form)`
display: grid;
grid-template-areas:
"message message"
"name email"
"actions actions";
grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
grid-gap: ${rhythm(1)};
`
const FormActions = styled.div`
grid-area: actions;
display: flex;
justify-content: flex-end;
`
export const ContactForm = ({ name = "contact", topContent = () => {} }) => {
const [isSuccess, setSuccess] = useState(false)
const [isError, setError] = useState(false)
const onSubmit = async values => {
setError(false)
try {
await fetch("/", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: encode({ "form-name": name, ...values }),
})
setSuccess(true)
} catch (err) {
console.error(err)
setError(true)
}
}
return (
<Formik
initialValues={{
name: "",
email: "",
message: "",
}}
validationSchema={validationSchema}
onSubmit={onSubmit}
>
{context => (
<>
{topContent(context, { isError, isSuccess })}
{!isSuccess && (
<>
<ErrorAlert
show={isError}
onClose={() => setError(false)}
message="There was an error sending your message. Please try again later."
/>
<StyledForm
name={name}
data-netlify="true"
data-netlify-honeypot="bot"
>
<Field name="name" label="Name" />
<Field name="email" label="Email" />
<Field name="message" label="Message" component="textarea" />
<FormActions>
<Button type="submit" icon={MdSend}>
Send
</Button>
</FormActions>
</StyledForm>
</>
)}
</>
)}
</Formik>
)
}