1.0.2 • Published 4 years ago

@react-toolkit/form-builder v1.0.2

Weekly downloads
-
License
MIT
Repository
github
Last release
4 years ago

A declarative way of building easy or complex forms with validations, group support and field logic for both React and React Native. You design the elements, the library does the rest.

Features

  • ZERO dependencies
  • Super lightweight library
  • Automatic validation of fields
  • Built-in validations + ability to easily to define custom validations
  • Supports grouping of fields
  • Supports hiding elements programmatically based on other fields
  • Wrap the form in any component (such as a form)
  • Easily get the field values in a dictionary and check for validation errors
  • Easily submit or reset the form
  • TypeScript syntax autocompletion

How to install

Open your terminal at the root of your React or React Native project and copy & paste the line below based on your preference.

# If you use npm
npm install --save @react-toolkit/form-builder

# If you use yarn
yarn add @react-toolkit/form-builder

How to use

Below is a React example but the same principles apply for React Native. You just need to update the Template, Input and Footer components to use the React Native ones.

// Import the library
import { Validators, Form } from '@react-toolkit/form-builder';

// Class code...

render() {
  const Template = ({ title, error, children }) => (
    <section>
      <label>{title}</label>
      <div>{children}</div>
      <span style={{ color: 'red' }}>{error}</span>
    </section>
  );

  const Input = ({ value, onValueChange, ...props }) => (
    <input
      {...props}
      value={value}
      onChange={e => onValueChange(e.target.value)}
    />
  );

  const Footer = ({ submit }) => (
    <button onClick={() => {
      const { values, hasErrors } = submit();
      if (!hasErrors) console.log(`Here are the values: ${values}`);
    }}>Submit</button>
  );

  // This is what you really need to write on each new form. The templates
  // and validators should be declared in a separate file and reused.
  return (
    <Form
      template={Template}
      footer={Footer}
      fields={[{
        key: 'firstName',
        validators: [Validators.requred()],
        item: Input,
        itemProps: { placeholder: 'First Name' },
        templateProps: { title: 'First Name' }
      }, {
        key: 'lastName',
        validators: [Validators.requred()],
        item: Input,
        itemProps: { placeholder: 'Last Name' },
        templateProps: { title: 'Last Name' }
      }]}
    />
  );
}

And that's how to create a simple form with two required fields and one submit button that prints the values in the console if there are no validation errors.

Properties

Form

Below are the props that the <Form /> component accepts

NameTypeRequiredDescription
fieldsarrayYesAn array of field elements
footercomponentNoDisplayed at the end of the form and will receive these props: { values, hasErrors, submit, reset }
groupcomponent or dictionaryNoEncapsulates the fields with the same group names within this component. You can specify a dictionary of components with the key being the group name that you want to use that component. Use global key as a fallback.
groupPropsdictionaryNoA dictionary of object values that are being sent as props to that respective group taken from the dictionary key
headercomponentNoDisplayed at the start of the form and will receive these props: { values, hasErrors, submit, reset }
onSubmitfunctionNoCalled when the form is submitted and has the following function argument: { values, hasErrors }
templatecomponentNoEncapsulates each field within this component and will receive these props: { error, ...templateProps }
wrappercomponentNoEncapsulates the entire form within this component and will receive these props: { values, hasErrors, submit, reset }

Field

A field indicates an user input to the form. This may be rendered as a text input, file input, checkbox, date picker, image picker, etc. You just need to show the value that the library provides and to ensure you call the onValueChange method when the value has changed (or on blur for huge/more optimized forms).

NameTypeRequiredDescription
groupstringNoThe group name
isHiddenfunctionNoA function that return a boolean and receives as an argument the values dictionary
itemcomponentYesRenders the item that will be displayed for user input and receives the following props: { value, onValueChange, error, ...itemProps }. You need to ensure that you show the value and call the onValueChange method once the value has changed.
itemPropsdictionaryNoThis is being passed to the item props
keystringYesThe unique field identifier
templatecomponentNoOverwrites the global template for this specific field
templatePropsdictionaryNoThis is being passed to the template props
validatorsarrayNoAn array of validator functions

Validator

The validator function receives a value as an argument and returns an optional string (which represents the validation error message). The value can be any type, it is the validator's job to check the type and to extract and verify the data from it.

const required = value => {
  if (!!value) return 'Field is required';
};

The built-in validators support overwriting the default error message and some of them need to be passed extra arguments. Below if an example of a validator that takes as arguments a number and a string and returns a validator function which compares the field value with the number passed as an argument.

const lessThan = (number, message = `Field must be less than ${number}`) => {
  return value => {
    if (typeof value === 'number' && value > number) {
      return message;
    }
  };
};

Contributions

If you want to improve the library or get involved you can do so by opening issues or creating pull requests with your code contributions. You are welcome to contribute in any way that improves the project as long as you are clear about your it and maintain the direction and simplicity of the library.

License

This project is licensed under MIT License. The license file can be found here.

1.0.2

5 years ago

1.0.0

5 years ago

1.0.1

5 years ago