Neglected Parking Meter

npm

Need private packages and team management tools?Check out npm Orgs. »

@byteclaw/forms

1.1.0 • Public • Published

@byteclaw/forms

CircleCI All Contributors Version License

Easily create complex forms in React.

Installation

npm install @byteclaw/forms yup
 
# or using yarn
 
yarn add @byteclaw/forms yup

Requirements

  • react >= 16.8.3

Up and running example

import { Fragment } from 'react';
import {
  ArrayField,
  Field,
  Form,
  FormProvider,
  ObjectField,
  createValidatorFromYup,
} from '@byteclaw/forms';
import * as yup from 'yup';
 
const validator = createValidatorFromYup(
  yup.object().shape({
    productTitle: yup.string().required(),
    images: yup
      .array()
      .of(
        yup.object().shape({
          title: yup.string().required(),
          url: yup
            .string()
            .url()
            .required(),
        }),
      )
      .required(),
    attributes: yup.object().shape({
      color: yup
        .string()
        .matches(/^#[0-9a-fA-F]{6}$/)
        .required(),
    }),
  }),
);
 
<Form onSubmit={async values => {}} onValidate={validator}>
  {/* global error of form */}
  <FieldError>{({ error }) => error || null}</FieldError>
  <Field name="productTitle" />
  <FieldError name="productTitle">{({ error }) => error || null}</FieldError>
  <ArrayField name="images">
    {({ value, addItem, removeItem }) => (
      <Fragment>
        {/* value can be undefined/null if is not initialized */}
        {(value || []).map((val, i) => (
          <ObjectField name={i}>
            <Field name="url" type="url" />
            <FieldError name="url">{({ error }) => error || null}</FieldError>
            <Field name="title" />
            <FieldError name="title">{({ error }) => error || null}</FieldError>
            <button onClick={() => removeItem(i)} type="button">
              Remove
            </button>
          </ObjectField>
        ))}
        <button onClick={() => addItem()} type="button">
          Add image
        </button>
      </Fragment>
    )}
  </ArrayField>
  <FieldError name="images">{({ error }) => error || null}</FieldError>
  <ObjectField name="attributes">
    <Field name="color" />
    <FieldError name="color">{({ error }) => error || null}</FieldError>
  </ObjectField>
  <FieldError name="attributes">{({ error }) => error || null}</FieldError>
  <FormProvider>
    {form => (
      <button disabled={form.changing || form.submitting || form.validating} type="submit">
        Save
      </button>
    )}
  </FormProvider>
</Form>;

Examples

Contributors


Michal Kvasničák

💬 💻 🎨 📖 💡 🤔 👀 ⚠️

Juraj Hríb

💬 🐛 💻 📖 🤔 👀

This project follows the all-contributors specification. Contributions of any kind welcome!

License

MIT License

install

npm i @byteclaw/forms

Downloadsweekly downloads

53

version

1.1.0

license

MIT

homepage

github.com

repository

Gitgithub

last publish

collaborators

  • avatar
  • avatar
Report a vulnerability