Telegram Group & Telegram Channel
🔥 Как ускорить работу с формами в 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



tg-me.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:
tg-me.com/React_lib/672

View MORE
Open in Telegram


React Telegram | DID YOU KNOW?

Date: |

China’s stock markets are some of the largest in the world, with total market capitalization reaching RMB 79 trillion (US$12.2 trillion) in 2020. China’s stock markets are seen as a crucial tool for driving economic growth, in particular for financing the country’s rapidly growing high-tech sectors.Although traditionally closed off to overseas investors, China’s financial markets have gradually been loosening restrictions over the past couple of decades. At the same time, reforms have sought to make it easier for Chinese companies to list on onshore stock exchanges, and new programs have been launched in attempts to lure some of China’s most coveted overseas-listed companies back to the country.

Tata Power whose core business is to generate, transmit and distribute electricity has made no money to investors in the last one decade. That is a big blunder considering it is one of the largest power generation companies in the country. One of the reasons is the company's huge debt levels which stood at ₹43,559 crore at the end of March 2021 compared to the company’s market capitalisation of ₹44,447 crore.

React from tr


Telegram React
FROM USA