react-hook-form
を使う
use client;
import {useForm, FieldValues} "react-hook-form"
export const Page = () => {
const {register, handleSubmit} = useForm();
const postToApi = async (fields:FieldValues) => {
....
}
return (
<form onSubmit={handleSubmit(postToApi)}>
<label>お名前</label>
<input type="text" {...register("username")}/>
<button>送信</button>
</form>
)
}
export default Page;
action
を使う(個人的にはこれがベストプラクティス)
use client;
export const Page = () => {
const postToApi = async (fields:FormData) => {
....
}
return (
<form action={postToApi}>
<label>お名前</label>
<input type="text" name="username"/>
<button>送信</button>
</form>
)
}
export default Page;
useState
を使う(記事ではよく見かけるがどうなんだろ..)
use client;
import {useState} from "react"
export const Page = () => {
const [username, setUsername] = useState<string>("");
const postToApi = async () => {
const parms = {
username: username,
...
}
....
}
return (
<form>
<label>お名前</label>
<input type="text" value={username} onChange={(e) => setUsername(e.target.value)}/>
<button type="button" onClick={postToApi}>送信</button>
</form>
)
}
export default Page;