Giter Club home page Giter Club logo

form-field-hooks's Introduction

form-field-hooks (React)

stateful input field hooks built with react-hooks, for ease of validations etc. (This is experimental for now, feel free to pr fixes and upgrades.)

Attributes and return types

Input fields:

(useInputuseSelectuseTextAreauseCheckbox)

Input Parameters:

property description
attributes: {} valid html input attributes
options:
{validations: (attr) => [boolean, string], display: (attr) => boolean}
these functions are called to
set meta and while sanitize()
React React's imported object (kinda necessary in the current version as it throws hooks related errors, would be fixed in the future)

Output Element:

property description
attr: {} html attributes
meta: {} meta data (stateful)
valid options below in meta table
dispatchAttr:
(...attr) => void
setState for attr
dispatchMeta:
(...meta) => void
setState for meta
dispatchOptions:
(...options) => void
setState for options
sanitize:
({valid?: boolean, show?: boolean}) => void
setState for meta,
(provided options run in this method)
fieldType: string type of html field
(input, checkbox, textarea etc)

Meta:

property description
touched: boolean if at all focused
dirty: boolean if value changed
valid: boolean is valid
show: boolean should display
customValidity
validationMessage: string
error message if valid is false

Note: validations work side by side with the ValidityState API and Constraint Validation API

(use options.validations instead of the validity API as it might break the behaviour of the hooks' meta).

Examples:

Import

import Form, {
  useInput,
  useSelect,
  useCheckbox,
  useTextArea
} from 'form-field-hooks';

validations and display

const InputElement = () => {
  const name = useInput(
    {value: '', name: 'passwd', type: 'password'},
    {
      // this is to set the properties of the field's `meta`
      validations: (attr) => {
        if (attr.value.length < 8) {
          return [false, 'should be atleast 8 characters long.'];
        }
        return [true, ''];
      },
      display: (attr) => {
        if (attr.className && attr.className.includes('hide-input'))
          return false;
        return true;
      }
    }, React
  );

  const { touched, dirty, show, valid } = name.meta;

  // An Example of how `meta can be useful`
  const style = {boderColor: (touched || dirty) && !valid ? 'red' : 'none'};

  return (
    <Fragment>

      {/* Form.Input takes care of not rendering the input if `show` is False */}

      <Form.Input element={name} style={style} react={React} />
      {(
        !meta.valid &&
        meta.validationMessage.length // we get to set this in `options.validations`
      ) ? <ErrorMessage msg={meta.validationMessage} /> : <></>}


      {/* Or using without `Form` */}

      {show && <input element={name} style={style} />}
    </Fragment>
  )
}

Using the Hooks

'useInput' (Input field, can be any <input /> except radio button)

const InputElements = () => {
  const name = useInput({value: 'luffy', name: 'name'}, {}, React);

  const isSaiyan = useCheckbox({name: 'isSaiyan', checked: true}, {}, React);
  const isSuper = useCheckbox({name: 'isSuper'}, {}, React);

  // Can be any Input Element
  // (text, checkbox, password, datetime
  // datetime-local, time, phone, checkbox etc)
  return (
    <Fragment>
      <Form.Input element={name} react={React} />
      <Form.Input element={isSuper} react={React} />
      <Form.Input element={isSaiyan} react={React} />
      
      {/** can also use
        * <input {...name.attr} />
        * <input {...isSuper.attr} />
        * <input {...isSaiyan.attr} />
        */}
    </Fragment>
  )
}

'useSelect' (<select /> field):

  const SelectElement = () => {
    const select = useSelect({value: '', name: 'select'}, {}, React);
    const multiselect = useSelect(
      {value: '', name: 'multiselect', multiple: true},
      {},
      React
    );

    return (
      <Fragment>
        {/*
          * Here the `defaultOption` attr will add
          * an extra null option
          * value: the value of the default option.
          * label: display value for the default option.
          * hideAfter: remove default option on any other value selection.
          */}

        <Form.Select
          element={select}
          defaultOption={{ value: '', label: '--', hideAfter: true}}
          react={React}
        >
          <option value='1'>One Piece</option>
          <option value='2'>Cowboy Bebop</option>
          <option value='3'>Death Note</option>
          <option value='4'>Naruto</option>
        </Form.Select>

        {/** can also use
          * <select {...multiselect.attr}>
          * ...
          * </select>
          */}
      </Fragment>
    )
  }

'useTextArea' (<textarea /> field)

  const TextAreaElement = () => {
    const description = useTextArea({value: '', name: 'description'}, {}, React);

    return (
      <Fragment>
        <Field.TextArea element={description} react={React} />

        {/** can also use
          * <textarea {...description.attr} />
          */}
      </Fragment>
    )
  }

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.