BasicArrays
Nested Array
Array di dalam object atau array lain.
Nested Array membuat daftar di dalam daftar. Setiap company pada contoh ini memiliki daftar kontak sendiri.
Penggunaan
Simpan form.tsx dan schema.ts di folder yang sama.
"use client";
import { useForm } from "@tanstack/react-form";
import { ErlForm } from "erlangform";
import { schema, type FormValues } from "./schema";
export default function CompaniesForm() {
const form = useForm({
defaultValues: {
companies: [
{
name: "ErlanggaTech",
contacts: [
{
type: "",
phone: "",
companyName: "",
active: false,
},
],
},
],
},
validators: { onChange: schema },
onSubmit: ({ value }) => alert(JSON.stringify(value, null, 2)),
});
return (
<form
className="demo-form"
onSubmit={(event) => {
event.preventDefault();
void form.handleSubmit();
}}
>
<ErlForm<FormValues>
form={form}
schema={schema}
fieldConfig={{
companies: {
section: "Daftar Perusahaan",
array: {
itemLabel: (item, index) =>
item.name ? item.name : `Perusahaan #${index + 1}`,
addLabel: "+ Tambah Perusahaan",
removeLabel: "Hapus Perusahaan",
},
name: {
label: "Nama Perusahaan",
placeholder: "PT Nama Perusahaan",
},
contacts: {
array: {
itemLabel: (_, index) => `Kontak perusahaan #${index + 1}`,
addLabel: "+ Tambah Kontak Perusahaan",
removeLabel: "Hapus Kontak",
},
type: {
label: "Tipe Kontak",
options: [
{ label: "Personal", value: "personal" },
{ label: "Perusahaan", value: "company" },
],
},
phone: {
label: "Nomor Telepon",
placeholder: "0812xxxxxxxx",
},
companyName: {
label: "Nama PT/CV",
placeholder: "PT Nama Kontak",
showIf: (contact) => contact.type === "company",
requiredIf: (contact) => contact.type === "company",
clearOnHide: true,
},
active: {
label: "Status Aktif",
},
},
}
}}
/>
<button type="submit" className="demo-button mt-4">Simpan</button>
</form>
);
}Bentuk defaultValues mengikuti schema, sampai ke array contacts. Nilai seperti companies[0].contacts[0].phone dikelola oleh TanStack Form. Konfigurasi field bersarang pada versi saat ini memakai nama field (contacts), bukan path lengkap.