-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathContactForm.jsx
More file actions
60 lines (54 loc) · 1.62 KB
/
Copy pathContactForm.jsx
File metadata and controls
60 lines (54 loc) · 1.62 KB
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
import { useState } from 'react'
export default function ContactForm({ handlerId }) {
const [status, setStatus] = useState('idle') // idle | sending | ok | error
const [message, setMessage] = useState('')
async function handleSubmit(e) {
e.preventDefault()
setStatus('sending')
const data = Object.fromEntries(new FormData(e.target))
try {
const res = await fetch(
`https://api.formhandle.dev/submit/${handlerId}`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
}
)
if (res.ok) {
setStatus('ok')
setMessage('Message sent! We\'ll get back to you soon.')
e.target.reset()
} else {
throw new Error(`Server returned ${res.status}`)
}
} catch {
setStatus('error')
setMessage('Something went wrong. Please try again.')
}
}
return (
<form onSubmit={handleSubmit}>
<div>
<label htmlFor="name">Name</label>
<input id="name" type="text" name="name" required />
</div>
<div>
<label htmlFor="email">Email</label>
<input id="email" type="email" name="email" required />
</div>
<div>
<label htmlFor="message">Message</label>
<textarea id="message" name="message" required />
</div>
<button type="submit" disabled={status === 'sending'}>
{status === 'sending' ? 'Sending...' : 'Send'}
</button>
{message && (
<p style={{ color: status === 'ok' ? '#065f46' : '#991b1b' }}>
{message}
</p>
)}
</form>
)
}