File size: 2,127 Bytes
1e92f2d |
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 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 |
import React from 'react';
import { useForm, ValidationMode } from 'react-hook-form';
import { useParams } from 'react-router-dom';
let renderCounter = 0;
const FormState = () => {
const { mode } = useParams();
const {
register,
handleSubmit,
formState: {
dirtyFields,
isSubmitted,
submitCount,
touchedFields,
isDirty,
isSubmitting,
isSubmitSuccessful,
isValid,
},
reset,
} = useForm<{
firstName: string;
lastName: string;
select: string;
radio: string | null;
checkbox: boolean;
['checkbox-checked']: boolean;
}>({
mode: mode as keyof ValidationMode,
defaultValues: {
firstName: '',
lastName: '',
select: '',
checkbox: false,
radio: null,
'checkbox-checked': true,
},
});
renderCounter++;
return (
<form
onSubmit={handleSubmit((d) => {
console.log(d);
})}
>
<input
{...register('firstName', { required: true })}
placeholder="firstName"
/>
<input
{...register('lastName', { required: true })}
placeholder="lastName"
/>
<div id="state">
{JSON.stringify({
isSubmitted,
submitCount,
isDirty,
isSubmitting,
isSubmitSuccessful,
isValid,
touched: Object.keys(touchedFields),
dirty: Object.keys(dirtyFields),
})}
</div>
<select {...register('select')} defaultValue="test">
<option value="">Select</option>
<option value="test">test</option>
<option value="test1">test1</option>
<option value="test2">test3</option>
</select>
<input type="radio" {...register('radio')} />
<input type="checkbox" {...register('checkbox')} />
<input type="checkbox" {...register('checkbox-checked')} />
<button id="submit">Submit</button>
<button type="button" onClick={() => reset()} id="resetForm">
Reset
</button>
<div id="renderCount">{renderCounter}</div>
</form>
);
};
export default FormState;
|