REACT_LIB Telegram 672
🔥 Как ускорить работу с формами в React

Я часто использую библиотеку react-hook-form, и одна из самых частых задач — это создание динамических списков полей (например, список контактов пользователя).
Раньше я писал кучу ручного кода для добавления/удаления элементов, пока не открыл для себя хук useFieldArray.

Пример использования:


import { useForm, useFieldArray } from "react-hook-form";

function ContactForm() {
const { control, register, handleSubmit } = useForm({
defaultValues: {
contacts: [{ value: "" }]
}
});
const { fields, append, remove } = useFieldArray({
control,
name: "contacts"
});

return (
<form onSubmit={handleSubmit(data => console.log(data))}>
{fields.map((field, index) => (
<div key={field.id}>
<input {...register(`contacts.${index}.value`)} />
<button type="button" onClick={() => remove(index)}>Удалить</button>
</div>
))}
<button type="button" onClick={() => append({ value: "" })}>Добавить контакт</button>
<button type="submit">Отправить</button>
</form>
);
}


Этот код автоматически управляет всеми id полей и обновляет форму без лишней боли!
Если раньше вы управляли массивами вручную — попробуйте useFieldArray, вы удивитесь, насколько это проще.

Пользуетесь ли вы react-hook-form или предпочитаете что-то другое для работы с формами?

✍️ @React_lib



tgoop.com/React_lib/672
Create:
Last Update:

🔥 Как ускорить работу с формами в React

Я часто использую библиотеку react-hook-form, и одна из самых частых задач — это создание динамических списков полей (например, список контактов пользователя).
Раньше я писал кучу ручного кода для добавления/удаления элементов, пока не открыл для себя хук useFieldArray.

Пример использования:


import { useForm, useFieldArray } from "react-hook-form";

function ContactForm() {
const { control, register, handleSubmit } = useForm({
defaultValues: {
contacts: [{ value: "" }]
}
});
const { fields, append, remove } = useFieldArray({
control,
name: "contacts"
});

return (
<form onSubmit={handleSubmit(data => console.log(data))}>
{fields.map((field, index) => (
<div key={field.id}>
<input {...register(`contacts.${index}.value`)} />
<button type="button" onClick={() => remove(index)}>Удалить</button>
</div>
))}
<button type="button" onClick={() => append({ value: "" })}>Добавить контакт</button>
<button type="submit">Отправить</button>
</form>
);
}


Этот код автоматически управляет всеми id полей и обновляет форму без лишней боли!
Если раньше вы управляли массивами вручную — попробуйте useFieldArray, вы удивитесь, насколько это проще.

Пользуетесь ли вы react-hook-form или предпочитаете что-то другое для работы с формами?

✍️ @React_lib

BY React




Share with your friend now:
tgoop.com/React_lib/672

View MORE
Open in Telegram


Telegram News

Date: |

Judge Hui described Ng as inciting others to “commit a massacre” with three posts teaching people to make “toxic chlorine gas bombs,” target police stations, police quarters and the city’s metro stations. This offence was “rather serious,” the court said. The group’s featured image is of a Pepe frog yelling, often referred to as the “REEEEEEE” meme. Pepe the Frog was created back in 2005 by Matt Furie and has since become an internet symbol for meme culture and “degen” culture. Joined by Telegram's representative in Brazil, Alan Campos, Perekopsky noted the platform was unable to cater to some of the TSE requests due to the company's operational setup. But Perekopsky added that these requests could be studied for future implementation. The visual aspect of channels is very critical. In fact, design is the first thing that a potential subscriber pays attention to, even though unconsciously. Invite up to 200 users from your contacts to join your channel
from us


Telegram React
FROM American