forked from vercel/next.js
/
js-form.tsx
61 lines (54 loc) · 1.85 KB
/
js-form.tsx
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
import Link from 'next/link'
import { FormEvent } from 'react'
import styles from '../styles/Home.module.css'
export default function PageWithJSbasedForm() {
// Handle the submit event on form submit.
const handleSubmit = async (event: FormEvent) => {
// Stop the form from submitting and refreshing the page.
event.preventDefault()
// Cast the event target to an html form
const form = event.target as HTMLFormElement
// Get data from the form.
const data = {
first: form.first.value as string,
last: form.last.value as string,
}
// Send the form data to our API and get a response.
const response = await fetch('/api/form', {
// Body of the request is the JSON data we created above.
body: JSON.stringify(data),
// Tell the server we're sending JSON.
headers: {
'Content-Type': 'application/json',
},
// The method is POST because we are sending data.
method: 'POST',
})
// Get the response data from server as JSON.
// If server returns the name submitted, that means the form works.
const result = await response.json()
alert(`Is this your full name: ${result.data}`)
}
return (
<div className="container">
<h1 className={styles.title}>
Form{' '}
<Link href="/">
<a>with</a>
</Link>{' '}
JavaScript.
</h1>
<p className={styles.description}>
Get started by looking at{' '}
<code className={styles.code}>pages/js-form.js</code>
</p>
<form onSubmit={handleSubmit}>
<label htmlFor="first">First Name</label>
<input type="text" id="first" name="first" required />
<label htmlFor="last">Last Name</label>
<input type="text" id="last" name="last" required />
<button type="submit">Submit</button>
</form>
</div>
)
}