React Hook Form İçin Kapsamlı Bir Rehber

React Hook Form Nedir ?

Kurulum

npm install react-hook-form

Temeller

import { useForm } from "react-hook-form"
const { register,handleSubmit} = useForm();
import React from "react";import { useForm } from "react-hook-form";export default function App() {const { register, handleSubmit } = useForm();const onSubmit = data => console.log(data);return ( <form onSubmit={handleSubmit(onSubmit)}>  <input " {...register("example_name")} />  <input {...register("example_name_2")} /> <input type="submit" /></form>);}
<input type="text" name="example_name" ref={register} />

Validasyonlar ve Hatalar

  • required : değerin mutlaka girilmesi gerekli olduğunu belirtir. (true/false)
  • min: sayısal değerler için maximum değerini belirtir.
  • max : sayısal değerler için maximum değerini belirtir.
  • minLength : değerin minimum uzunuluğunu belirtir.
  • maxLength : değerin maksimum uzunuluğunu belirtir.
  • validate : callback fonksiyonu ile validasyon yapabilirsin
<input {…register(“test”, { validate: value => value === ‘1’ })} />
{…register(“example_name”, validasyon : {value : değeri , message : hata_mesajı})}
import React from “react”;import { useForm } from “react-hook-form”;export default function App() {const { register, handleSubmit, formState: { errors } } = useForm();const onSubmit = data => console.log(data);return (  <form onSubmit={handleSubmit(onSubmit)}><input type={“text”} {…register(“username”,{required:{message:”kullanıcı adı gereklidir”,value:true})} />     {        errors.username?.message     }    <input type=”submit” /></form>);}
const { register, handleSubmit,formState: { errors } } = useForm();
<input type={“text”} {…register(“username”,{required:{message:”kullanıcı adı gereklidir”,value:true})} />

Schema Validasyonu

npm install @hookform/resolvers yup
const schema = yup.object().shape({
firstName: yup.string().required(),
age: yup.number().positive().integer().required(), }).required();
const { register, handleSubmit, errors } = useForm({ 
resolver: yupResolver(schema) });
<input {…register(“firstName”)} />
import React from “react”; 
import { useForm } from “react-hook-form”;
import { yupResolver } from ‘@hookform/resolvers/yup’;
import * as yup from “yup”;
const schema = yup.object().shape({
firstName: yup.string().required(), age: yup.number().positive().integer().required(),
}).required();
export default function App() { const { register, handleSubmit, errors } = useForm({ resolver: yupResolver(schema) }); const onSubmit = data => console.log(data); return ( <form onSubmit={handleSubmit(onSubmit)}> <input {...register("firstName")} /> <p>{errors.firstName?.message}</p> <input {...register("age")} />

<p>{errors.age?.message}</p> <input type=”submit” />
</form>
); }

Varolan Bir Kompanenti Entegre Etme

const Input = ({ label, register, required }) => (
<>
<label>{label}</label>
<input {...register(label, { required })} />
</>
);
const Select = React.forwardRef(({ onChange, onBlur, name, label }, ref) => (
<>
<label>{label}</label>
<select name={name} ref={ref} onChange={onChange} onBlur={onBlur}>
<option value="20">20</option>
<option value="30">30</option>
</select>
</>
));
const App = () => {
const { register, handleSubmit } = useForm();
const onSubmit = (data) => {
alert(JSON.stringify(data));
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<Input label="First Name" register={register} required /> <Select label="Age" {...register("Age")} /> <input type="submit" />
</form>
);
};

UI Kütüphaneleriyle Kullanmak

import { useForm, Controller } from “react-hook-form”;
import Input from "@material-ui/core/Input";
const { control, handleSubmit } = useForm();
<Controller
name="firstName"
control={control}
render={({ field }) => <Input {...field} />}
/>
import React from "react";
import Select from "react-select";
import { useForm, Controller } from "react-hook-form";
import Input from "@material-ui/core/Input";
const App = () => {
const { control, handleSubmit } = useForm({
defaultValues: {
firstName: '',
select: {}
}
});
const onSubmit = data => console.log(data);
return (
<form onSubmit={handleSubmit(onSubmit)}>
<Controller
name="firstName"
control={control}
render={({ field }) => <Input {...field} />}
/>
// İŞTE BAŞKA BİR ÖRNEK <Controller
name="select"
control={control}
render={({ field }) => <Select
{...field}
options={[
{ value: "chocolate", label: "Chocolate" },
{ value: "strawberry", label: "Strawberry" },
{ value: "vanilla", label: "Vanilla" }
]}
/>}
/>

<input type="submit" />
</form>
);
};

useController Hook’unun Kullanımı

import React from "react";
import { TextField } from "@material-ui/core";
import { useController, useForm } from "react-hook-form";
function Input({ control, name }) {
const {
field: { onChange, onBlur, name, value, ref },
fieldState: { invalid, isTouched, isDirty },
formState: { touchedFields, dirtyFields }
} = useController({
name,
control,
rules: { required: true },
defaultValue: "",
});
return (
<TextField
onChange={onChange}
onBlur={onBlur}
value={value}
name={name}
inputRef={ref}
/>
);
}

Nested Forms — İç İçe Yapılar

import { useForm, FormProvider, useFormContext } from "react-hook-form";
<FormProvider {...methods} > // pass all methods into the context
<form onSubmit={methods.handleSubmit(onSubmit)}>
<NestedInput />
<input type="submit" />
</form>
</FormProvider>
function NestedInput() {
const { register } = useFormContext(); // retrieve all hook methods
return <input {...register("test")} />;
}
import React from "react";
import { useForm, FormProvider, useFormContext } from "react-hook-form";
export default function App() {
const methods = useForm();
const onSubmit = data => console.log(data);
return (
<FormProvider {...methods} > // pass all methods into the context
<form onSubmit={methods.handleSubmit(onSubmit)}>
<NestedInput />
<input type="submit" />
</form>
</FormProvider>
);
}
function NestedInput() {
const { register } = useFormContext(); // retrieve all hook methods
return <input {...register("test")} />;
}

--

--

Frontend Deveoper

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store