forked from Mosquid/react-form-wp-cf7
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cf7-form-wrapper.js
69 lines (57 loc) · 1.47 KB
/
cf7-form-wrapper.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
import React, { cloneElement, useState } from "react"
const jsonToFormData = (json) => {
try {
const data = new FormData()
for (let k in json) {
data.append(k, json[k])
}
return data
} catch (error) {
console.error(error)
return null
}
}
const ErrorMessage = () => {
return (
<div style={{ color: "red" }}>
<strong>url</strong> or <strong>siteUrl</strong> and{" "}
<strong>formId</strong> are mandatory attributes
</div>
)
}
const Cf7FormWrapper = ({ children, siteUrl, formId, url }) => {
const [isSent, setSent] = useState(false)
const [isLoading, setLoading] = useState(false)
const [hasError, setError] = useState(null)
const apiUrl =
url ||
`${siteUrl}/wp-json/contact-form-7/v1/contact-forms/${formId}/feedback/`
const formSubmitHandler = (event, payload) => {
event.preventDefault()
setLoading(true)
setError(null)
fetch(apiUrl, {
method: "POST",
body: jsonToFormData(payload),
})
.then((resp) => resp.json())
.then((resp) => {
if (resp.status !== "mail_sent") throw resp.message
setSent(true)
})
.catch((error) => {
setError(error)
})
.finally(() => {
setLoading(false)
})
}
const Form = cloneElement(children, {
handler: formSubmitHandler,
isLoading,
isSent,
hasError,
})
return <div>{url || (siteUrl && formId) ? Form : <ErrorMessage />}</div>
}
export default Cf7FormWrapper