1.0.1 • Published 4 years ago

react-forms-element v1.0.1

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

React forms element

Flexible and customizable component to create forms easily.

Demo

There is a demo with some examples and a form creator here. The repo with the code is this one.

Quickstart

import React, { FunctionComponent, ReactElement } from 'react';
import './App.scss';
import { FormComponent, Field } from 'react-forms-element';

const validatePassword = (password: string): string => {
  return password.length < 6 ? 'short_pwd' : '';
}

const App: FunctionComponent = (): ReactElement => {
  const fields: Field[] = [
    { content: <div><h1>FORM EXAMPLE</h1></div>, type: 'custom' },
    { value: '', label: 'Name', name: 'name', type: 'string', required: true },
    { value: '', label: 'Password', name: 'pwd', type: 'password', required: true, customValidator: validatePassword, inputType: 'password' },
    { value: '', label: 'Business', name: 'business', type: 'checkbox', required: true }
  ];
  const errors = {
    short_pwd: 'Password too short'
  };

  const onSubmit = (form: any): any => console.log(form);

  return <div className="App">
      <FormComponent fields={fields} onSubmit={onSubmit} errors={errors} />
  </div>;
};

export default App;

Props and model

Default errors

NameDefaultDescription
required_fieldRequired fieldError message to show when a field is not set and is required.
wrong_emailWrong email formatError message to show when a field is of type email and the format is wrong.
wrong_numberWrong number formatError message to show when a field is of type number and the value is not a number.
wrong_min_nMin value is nError message to show when a field is of type number and the value is lower than the min.
wrong_max_nMax value is nError message to show when a field is of type number and the value is higher than the max.
no_selectedSelect one optionError message to show when a field is of type select and no option is selected.
no_file_selectedSelect a fileError message to show when a field is of type file and no file is selected.

FormComponent props

NameTypeRequiredDefaultDescription
fieldsField[]true-The array of fields to create the form and display.
onSubmitFunctiontrue-The function to call when the form is submitted. It can return a JSON with errors where the key is the field name and the value the error code, if you want to show a non specific field error set the message in the generalError property of the JSON.
classNamestringfalse-The class to add to the form main div.
errorsRecord<string, string>falseDefault errors ↑A JSON containing the error messages, if one of above is specified it will be used, if not the default will be used. If one of your custom validations return a custom message it has to be added in this JSON (if it is not found the form will show the returned string).
calendarLocaleanyfalsedate-fns/locale/en-USThe calendar config for the date input, use the date-fns/locale option you need (check th examples).
submitButtonTextstringfalseSENDThe submit button text.

Field model

NameTypeRequiredDefaultDescription
namestringtrue-Name of the field, the returned JSON on submit will have the according value in this field. It MUST be unique.
valueanyfalse-Value of the field when creating the form, more details in the next table.
type'string' | 'textarea' | 'number' | 'select' | 'date' | 'checkbox' | 'file' | 'email' | 'checkbox-list' | 'list' | 'custom'falsestringType of the field that determines the type of input.
classNamestringfalse-Class to add to the field container.
placeholderstringfalse-Placeholder of the input.
titlestringfalse-Title for the fields of type list.
addButtonstringfalseADDText of the submit button for a list field.
labelstring | ReactElementfalse-Label for the field.
requiredbooleanfalsefalseWhether the field is required or not.
fileTypestringfalse-Accepted file types.
multipleFilesbooleanfalsefalseWhether to allow multiple file selection or not.
multipleSelectedbooleanfalsefalseWheter to allow multiple option selection or not.
inputTypestringfalse-Type of the HTML input (for example, set tel if you want to display numbers keyboard in mobile devices).
customValidatorFunctionfalse-A function to validate the field, it will be executed on blur and on submit. If it returns a string or a Promise, the field error will contain this string, if not the default validation will be executed.
contentReactElementfalse-The content to show for fields whose type is custom.
options{label: any, value: any}[]false-The array of options to show for a select or a checkbox-list input.
minnumberfalse-The min value of the input.
maxnumberfalse-The max value of the input.
stepnumberfalse-The step of the input for number fields.
mobileCalendarbooleanfalse-Whether to show a different mobile friendly calendar or not when the screen width is small.
minDateDatefalse-Min date for date input.
maxDateDatefalse-Max date for date input.
onChangeFunctionfalse-Function to call when the field value changes.
onBlurFunctionfalse-Function to call when the field blur event is triggered.
fieldsField[]false-Fields to show for a list component, more details in the next table.
showInListbooleanfalse-Fields of type list show a table with the current value, only the values of the fields with showInList as true will be shown.
listLabelstringfalse-Fields of type list show a table with the current value, listLabel will be shown in the table header. If it is not defined label will be set as header for this field.
formatDateFunctionfalse-Function to call when showing a date in the list table of values.
dateFormatstringfalsedd/MM/yyyyDate format for the date input.
onSubmitFunctionfalse-Function called when the form of a list element is submitted.

Field types

TypeAccepted valuesDescription
stringstringThe string value.
textareastringThe string value.
emailstringThe email value.
numberstring | numberThe number value, if it is not a valid number the validation will fail.
emailstringThe email value.
selectanyThe selected value of the select input when it is not multipleSelected.
selectany[]The array of the selected values of the select input when it is multipleSelected.
dateDateThe date value.
checkboxbooleanThe checkbox value.
checkbox-liststring[]The checkbox selected values.
fileFile | stringThe File object or an url of the file.
fileFile[] | string[]The array of file objects or urls.
listany[]The array of custom objects.

Custom styling

Provide a className attribute to the field you want to style or override the classes used by default:

ClassElement
form-componentThe main div that contains the form.
fieldContainer of the input.
input-errorSet to the input elements to paint the border when there is an error.
titleTitle of the a list field.
submit-containerContainer of the submit button.
errorError messages.
select-componentContainer of the select input.
date-componentContainer of the date input.
file-componentContainer of the file input.
list-componentContainer of the list input.
checkbox-componentContainer of the checkbox input.

Support

Did you enjoy React Forms Element? Do you find it useful? Feel free to contribute and buy me a cup of coffee if you want to help!