File size: 2,000 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 |
import React from 'react';
import { useForm, useFieldArray } from 'react-hook-form';
import { object, array, string } from 'yup';
import { yupResolver } from '@hookform/resolvers';
const validationSchema = object().shape({
questions: array()
.of(
object().shape({
text: string().required('Some text is required'),
}),
)
.required(),
});
function App() {
const {
control,
register,
errors,
clearErrors,
setValue,
unregister,
handleSubmit,
trigger,
} = useForm({
mode: 'onChange',
resolver: yupResolver(validationSchema),
});
const { fields, append, remove } = useFieldArray({
control,
name: 'questions',
});
const isInitialRender = React.useRef(true);
const appendQuestion = () => {
append({
text: '',
});
if (errors.questions?.type === 'min') {
clearErrors('questions'); // always clear errors when there is add action.
}
};
React.useEffect(() => {
if (!fields.length && !isInitialRender.current) {
trigger('questions');
}
if (isInitialRender.current) {
isInitialRender.current = false;
}
}, [fields, register, setValue, unregister, trigger]);
return (
<form onSubmit={handleSubmit(console.log)}>
<h1>Yup Validation - Field Array</h1>
{fields.map((question, questionIndex) => (
<div key={question.id}>
<input
ref={register()}
name={`questions[${questionIndex}].text`}
control={control}
defaultValue=""
/>
<button
type="button"
onClick={() => {
remove(questionIndex);
trigger();
}}
>
Remove question {question.id}
</button>
</div>
))}
<p>Errors: {JSON.stringify(errors)}</p>
<button type="button" onClick={appendQuestion}>
Add question
</button>
<input type="submit" />
</form>
);
}
|