Skip to content

1.5.0

Compare
Choose a tag to compare
@pedro-lb pedro-lb released this 20 Jul 22:24
· 100 commits to master since this release

πŸ”₯ Support for array fields!

Formup now supports array fields! You can check all implementation details here.

Suppose you have an array in your schema, be it a simple array of primitive or string types, or an array of objects.

import * as yup from 'yup';

const familyMemberSchema = yup.object().shape({
  name: yup.string()
    .required()
    .label('Name'),

  email: yup.string()
    .email()
    .label('Email'),
}, locale);

const schema = yup.object().shape({
  // Array of strings
  colors: yup.array()
    .of(
      yup
        .string()
        .required(),
    ),

  // Array of objects
  familyMembers: yup.array()
    .of(familyMemberSchema),
});

You can now easily render these fields using FormArrayField, which is exported by useFormup:

const Example = () => {
  const {
    FormArrayField,
    formikForm,
    FormInput,
    Form,
  } = useFormup(schema);

  return (
    <Form formikForm={formikForm}>
      {/* Render array of strings */}
      <FormArrayField name="colors">
        {(items, arrayHelpers) => (
          <>
            {items.map((item, index) => (
              <div key={item.path}>
                <FormInput name={item.path} />

                <button
                  onClick={() => arrayHelpers.remove(index)}
                  type="button"
                >
                  Remove item
                </button>
              </div>
            ))}

            <button
              onClick={() => arrayHelpers.push()}
              type="button"
            >
              Add item
            </button>
          </>
        )}
      </FormArrayField>

      {/* Render array of objects */}
      <FormArrayField name="familyMembers">
        {(items, arrayHelpers) => (
          <>
            {items.map((item, index) => (
              <div key={item.path}>
                <FormInput name={item.getPath('name')} />

                <FormInput name={item.getPath('email')} />

                <button
                  onClick={() => arrayHelpers.remove(index)}
                  type="button"
                >
                  Remove family member
                </button>
              </div>
            ))}

            <button
              type="button"
              onClick={() => arrayHelpers.push({
                email: '[email protected]',
                name: 'Foo bar',
              })}
            >
              Add new family member
            </button>
          </>
        )}
      </FormArrayField>
    </Form>
  );
};

πŸ’… Improvements

  • πŸ’… FormInput component now validates if the field passed by "name" exists within the schema.

  • πŸ’… FormInputGroup component now validates if the field passed by "name" exists within the schema.

  • πŸ’… yup version was bumped to 0.29.1.

  • πŸ’… Removed unnecessary dependencies.