Skip to main content

Complex Structures

With React Cool Form you can use dot-and-bracket notation as the name of a field to create arbitrarily deeply a fields. It's very similar to Lodash's _.set method.

tip

Setting undefined as a field value deletes the field data from the structure (see related doc).

NameCurrent structureValueResult
foo{ }"rcf"{ foo: "rcf" }
foo.bar{ }"rcf"{ foo: { bar: "rcf" } }
foo[0]{ }"rcf"{ foo: [ "rcf" ] }
foo[1]{ }"rcf"{ foo: [ empty, "rcf" ] }
foo.0{ }"rcf"{ foo: [ "rcf" ] }
foo[0].bar{ }"rcf"{ foo: [ { bar: "rcf" } ] }
foo{ foo: "rcf" }undefined{ }
foo.bar{ foo: { bar: "rcf" }, baz: "rcf" }undefined{ baz: "rcf" }
foo[0]{ foo: [ { bar: "rcf" } ] }undefined{ foo: [ empty ] }

You can play around with the following example to get better understanding of how it works:

Edit RCF - Complex Structures

import { useForm } from "react-cool-form";
const FieldGroup = ({ name, onUpdate, onClear }) => (  <>    <input name={name} placeholder={name} />    <div>      <button type="button" onClick={onUpdate}>        Update      </button>      <button type="button" onClick={onClear}>        Clear      </button>    </div>  </>);
const App = () => {  const { form, setValue } = useForm({    defaultValues: {      foo: "",      bar: [],      baz: { a: "" },      qux: [{ a: "" }],    },    onSubmit: (values) => console.log("onSubmit: ", values),  });
  return (    <form ref={form}>      <FieldGroup        name="foo"        onUpdate={() => setValue("foo", "rcf")}        onClear={() => setValue("foo")}      />      <FieldGroup        name="bar[0]"        onUpdate={() => setValue("bar[0]", "๐Ÿ‹")}        onClear={() => setValue("bar[0]")}      />      <FieldGroup        name="baz.a"        onUpdate={() => setValue("baz.a", "๐Ÿ‰")}        onClear={() => setValue("baz.a")}      />      <FieldGroup        name="qux[0].a"        onUpdate={() => setValue("qux[0].a", "๐Ÿฅ")}        onClear={() => setValue("qux[0].a")}      />      <input type="submit" />    </form>  );};