React quản lý Form với React Hook Form

Cài đặt

Việc cài đặt React Hook Form chỉ cần một lệnh duy nhất và bạn đã sẵn sàng sử dụng. 

npm install react-hook-form


import { useForm, SubmitHandler } from "react-hook-form"



type Inputs = {

  example: string

  exampleRequired: string

}



export default function App() {

  const {

    register,

    handleSubmit,

    watch,

    formState: { errors },

  } = useForm<Inputs>()

  const onSubmit: SubmitHandler<Inputs> = (data) => console.log(data)



  console.log(watch("example")) // watch input value by passing the name of it



  return (

    /* "handleSubmit" will validate your inputs before invoking "onSubmit" */

    <form {handleSubmit(onSubmit)}>

      {/* register your input into the hook by invoking the "register" function */}

      <input defaultValue="test" {...register("example")} />



      {/* include validation with required or other standard HTML validation rules */}

      <input {...register("exampleRequired", { required: true })} />

      {/* errors will return when field validation fails  */}

      {errors.exampleRequired && <span>This field is required</span>}



      <input type="submit" />

    </form>

  )

}

BÌNH LUẬN







Logo sangtacviet

sangtacviet.com là trang web cung cấp dịch vụ dịch tự động dịch truyện chữ trung.
Hướng dẫn tân thủ Bài viết App Extension Chọn ngôn ngữ