3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Next.jsがReact19に対応したので、Formのベストプラクティスを考えてみた。

Posted at

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;
3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?