0.3.1 • Published 2 years ago

form-full v0.3.1

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

Installation

Form-Full is available as an npm package.

// with npm
npm install form-full

// with yarn
yarn add form-full

How It Works

First, it is important to understand how each part interacts with the other.

There are four main parts which are as follows:

FormFull documentation React component that must encompass the entire form that will manage

useFormFull.field documentation Hook that will connect a new value input component (TextField, RadioButton, Checkbox... and everything else your project needs to use in the form)

useFormFull.button documentation Hook that will connect a new action component (Buttons and components that use onClick and need to interact with the form)

Handler Methods documentation // In process of development Class that manages all form behavior (Accessible by saving with the formRef of the FormFull component or in calls like onChange and onBlur of the input or field validations (validation or asyncValidation).

You can preview using the form and how to create form-full components in this interactive demo: Edit Button

Usage

import React from "react";
import { sleep } from "./utils";
import { FormFull } from "form-full";
import "./styles.css";
import Input from "./fields/Input";
import Button from "./buttons/Button";

export default function App() {
  const [currentValues, setCurrentValues] = React.useState({});
  const [savedValues, setSavedValues] = React.useState();
  const [disabledForm, setDisabledForm] = React.useState(false);

  function simulateRequest() {
    setCurrentValues(null);
    sleep(2000).then(() => {
      setCurrentValues({
        name: "Form Full",
        age: "18",
      });
    });
  }

  return (
    <div className='App'>
      <div className='form-container'>
        <FormFull
          disabled={disabledForm}
          currentValues={currentValues}
          onSubmit={(data) => {
            setSavedValues(data);
          }}>
          <div className='inputs-container'>
            <Input name='name' label='Your name' required='Required field' />
            <Input name='age' label='Your age' />
            <Input
              name='defaultValue'
              label='Default Value'
              defaultValue='Some Value'
            />
          </div>
          <Button action='submit' feedback>
            Submit
          </Button>
          <Button action='clear'>Clear All Values</Button>
          <Button action='clearDefault'>Set All Values to Default</Button>
          <Button onClick={() => simulateRequest()}>
            Simulate data from API
          </Button>
          <Button onClick={() => setDisabledForm(!disabledForm)}>
            {disabledForm ? "Enable Form" : "Disable Form"}
          </Button>
        </FormFull>
      </div>

      <div>
        <h3>
          {!!savedValues
            ? "Values ​​that were saved when sending the data."
            : "Submit the values ​​correctly to view the data that was sent."}
        </h3>
        {!!savedValues && <p>{JSON.stringify(savedValues)}</p>}
      </div>
    </div>
  );
}

First of all it will be necessary to create components that connect with form-full

Example of an "Input" component

import React from "react";
import { useFormFull } from "form-full";

function getErrorClassname(base, error, valid) {
  const className = base;
  if (error) return `${className} invalid`;
  if (valid) return `${className} valid`;
  return className;
}

function getHint(error, valid) {
  if (error) return error;
  if (valid) return "Valid value.";
  return null;
}

function Input(props) {
  const {
    value,
    error,
    valid,
    onSubmit,
    onBlur,
    onChange,
    testFieldError,
    ref,
    formDisabled,
    formLoading,
    // ffHandler, If some extra treatment is needed
  } = useFormFull.field(props);

  const { label, required, name } = props;

  return (
    <div className={getErrorClassname("form-control", error, valid)}>
      <label for={name} className='form-input-label'>
        {label} {!!required ? "*" : ""}
      </label>
      <input
        name={name}
        label={label}
        value={value}
        ref={ref}
        required={!!required}
        disabled={formDisabled || formLoading}
        onKeyPress={onSubmit}
        onChange={(event) => {
          onChange(event, event.target.value);
          if (props.validateOnChange) {
            testFieldError();
          }
        }}
        onBlur={onBlur}
        className='form-input'
      />
      <span className='form-input-hint'>{getHint(error, valid)}</span>
    </div>
  );
}

export default React.memo(Input);

Example of an "Button" component

import { useFormFull } from "form-full";

function Button({
  children,
  action,
  feedback,
  onClick: onClickProps,
  ...props
}) {
  const { onClick, formLoading, formDisabled } = useFormFull.button({
    feedback,
    action,
    onClick: onClickProps,
  });

  return (
    <button
      {...props}
      className='button'
      disabled={formDisabled}
      onClick={formLoading ? null : onClick}>
      {formLoading ? "Loading..." : children}
    </button>
  );
}

export default React.memo(Button);

Documentation

FormFull

props passed to the component that manages the form:

NameTypeRequiredDescription
currentValuesobjectnoObject that defines the current values ​​of each field in the form. example: { username: "form", password: "full123" }. important: Values ​​will only be inserted into the field if they change from the previous currentValues.
childrenReactNodeyesRendered components. All fields and buttons on the form must be children of the FormFull component
clearOnSubmitboolnoIf true is passed, the fields will be cleared (or filled in by default) when submitting the form
disabledboolnoIf true is passed, all fields will be disabled
formReffuncnoFunction to get the class that manages the form, normally used to handle exceptions and others advanced treatments
onSubmitfuncyesFunction called when the form is submitted, receiving the values ​​in a object { key: value }
onChangefuncnoFunction called when the value of any field changes
submitOnClearboolnoIf true is passed, the function onSubmit will be called when the form is cleared. **Only works if all fields are optional

Use FormFull Field

useFormFull.field Hook used to connect a field component to be controlled by form-full

Receives an object as a parameter with the properties:

NameTypeRequiredDescription
asyncValidationfuncnoused to validate input asynchronously (such as validating the existence of the username in a registration). Important: Like validation, need to return a string (if invalid) or null / undefined (if valid).
defaultValueanynoDefault field value. Value the component starts when it is first rendered
labelstringno/yesLabel used to concat errors message in a single object. Used to display all errors in a custom way. Important: label is required if placeholder is not passed
maskfuncnoFunction to format the end-user visible value
maskToSubmitfuncnoFunction to treat value when the form is submitted, converting it to the most suitable value for the developer
maxLengthnumbernoLimits the number of characters in the field. It is a native parameter, but form-full also uses it
namestringyesField name to be managed by the form. When the form is submitted the value will be inserted in a key of this name
onBlurfuncnoFunction that will be called when the input loses focus. It is necessary to pass to useFormFull.field and not use it directly in the field
onChangefuncnoFunction that will be called when the input value changes. It is necessary to pass to useFormFull.field and not use it directly in the field
placeholderstringno/yesReplaces and is required if the label is not passed
requiredstringnoError message that defines the field as required. It will be shown whenever the field validation is called and only if it is not filled.
submitOnBlurboolnoIftrueis passed the form will be submitted when field loses focus.
validationfuncnoUsed to validate input. Important: LikeasyncValidation, need to return a string (if invalid) or null / undefined (if valid).

Returns an object with properties:

NameTypeDescription
errorstring / nullError message to control field input feedback. string (if invalid) or null / undefined (if valid)
ffHandlerobjectForm handler ref to treat exceptions if needed
formDisabledboolControl boolean if the form is disabled. Suggestion of use: Block user action with the field
formLoadingboolControl boolean if the field is loading (with async validations). Suggestion of use: Block user action with the field and show visual loading feedback
onBlurfuncControls onBlur treatments on fields that use this listener. Needs to be passed as props for the field: onBlur={onBlur}
onChangefuncControls the change of field value. receives the event change as the first parameter and the new value as the second. the event is not used internally, it is passed on for external use only, if necessary.
onSubmitfuncControls the submission of the form from an action in the field: onKeyPress={onSubmit} (React JS) or onSubmitEditing={onSubmit} (React Native)
refReact.MutableRefObjectReact ref to control field focus when get validation error
testFieldErrorfuncFunction to call field validation. Important: Used only when the field does not have the onBlur listener and don't use the onBlur that the useFormFull.field returns
validboolControls whether the field is valid. Used to provide visual feedback when the field is filled in correctly
valueanyValue saved in the form. Example: value={value}

Use FormFull Button

useFormFull.button Hook used to connect a button component to be controlled by form-full

Receives an object as a parameter with the properties:

NameTypeRequiredDescription
actionstring / nullnoDefines what type of action the button will perform when clicked. Possible values: submit (calls FormFull's onSubmit), clear (clear all field values) and clearDefault (clear all values to default values). If none is passed it will not take any action, it is necessary to pass an onClick for it to have some action
feedbackbooleanno` | If true, button will receive update in styles and will be blocked while form is being submitted
onClickfuncnoFunction that will be called when the button is clicked. It is necessary to pass to useFormFull.button and not use it directly in the button rendered

Returns an object with properties:

NameTypeDescription
ffHandlerobjectForm handler ref to treat exceptions if needed
formDisabledboolControl boolean if the form is disabled. Suggestion of use: Block user action with the button
formLoadingboolControl boolean if the form is loading (with async validations). Suggestion of use: Block user action with the button and show visual loading feedback
onClickfuncControls onClick treatments on button. Needs to be passed as props for the button: onClick={onClick} (React JS) or onPress={onClick} (React Native)

Handler Methods

Method NameParamsReturnDescription
clearFields(setDefault: boolean = true)void//TODO
clearSpecificFields(names: Array, setDefault: boolean = true)void//TODO
clearValue(name: string, setDefault: bool = true)void//TODO
getActualValue(name: string)any//TODO
getDisabledFormbool//TODO
getFieldRefReact.MutableRefObject / null//TODO
getValidValues(valuesWithMaskToSubmit: boolean)Object<name: string: any>//TODO
getValue(name: string, withMaskToSubmit: boolean)void//TODO
getValuesObject<name: string: any>//TODO
removeButton(name: string)void//TODO
removeField(name: string)void//TODO
setCurrentValues(currentValues: Object<name: string: any>)void//TODO
setFieldAsyncValidation(name: string, asyncValidation: func)void//TODO
setFieldDefaultValue(name: string, defaultValue: any)void//TODO
setFieldFocus(name: string)void//TODO
setFieldLabel(name: string, label: string)void//TODO
setFieldMask(name: string, mask: func)void//TODO
setFieldMaskToSubmit(name: string, maskToSubmit: func)void//TODO
setFieldRequired(name: string, required: string / null / undefined)void//TODO
setFieldValidation(name: string, asyncValidation: func)void//TODO
setFormDisabled(disabled: boolean)void//TODO
setFormValue(name: string, value: any)void//TODO
setNewButton(name: string, buttonParams: Object)void//TODO
setNewField(name: string, buttonParams: Object)void//TODO
setValue(name: string, value: any)void//TODO
submitPromise//TODO
testErrorsAndReturnDataPromise<{hasError: boolean;data: Object<name: string: any>;}>//TODO
testFieldError(name: string, shouldUpdateInput: boolean = true)Promise<string / null / undefined>//TODO
0.3.0

2 years ago

0.3.1

2 years ago

0.2.1

2 years ago

0.2.0

2 years ago

0.2.2

2 years ago

0.1.2

3 years ago

0.1.1

3 years ago

0.1.4

3 years ago

0.1.3

3 years ago

0.1.5

3 years ago

0.1.0

3 years ago

0.0.9

3 years ago

0.0.8

3 years ago

0.0.7

3 years ago

0.0.5

3 years ago

0.0.4

3 years ago

0.0.6

3 years ago

0.0.3

3 years ago

0.0.2

3 years ago

0.0.1

3 years ago