0.0.3 • Published 5 years ago

react-fieldz v0.0.3

Weekly downloads
2
License
ISC
Repository
github
Last release
5 years ago

react-fieldz

react-fieldz is a library built off of fieldz.

It provides the useFieldz react hook, which simply wraps fieldz in React's useState.

Please see fieldz for more detail on the api.

Example Usage

const fieldProperties = {
  firstName: {
    init: "",
    validate: nameValidator
  },
  customField: {
    validate: (val: string) => {
      if (val !== "hello") {
        return [new Error("value must be hello!")]
      }
      return []
    },
    init: "this is my init value"
  }
}


const camelToTitle = camelCase => camelCase
    .replace(/([A-Z])/g, match => ` ${match}`)
    .replace(/^./g, match => match.toUpperCase())
    .trim()

const Form = () => {
  const [{actions, fieldsState}, setFieldsState] = useFieldz(fieldProperties)
  const {setValue, setValues, setTouched, resetField, resetFields } = actions

  return (
    <form>
      {Object.entries(fieldsState)
        .map(([fieldName, {errors, value, touched, pristine}]) => (
          <div key={fieldName}>
            {(touched && errors.length) ?
              <span className="input-error">
                {errors.map(err => <div>{err.toString()}</div>)}
              </span> : ""
            }
            <label htmlFor={fieldName}>{camelToTitle(fieldName)}</label>
            <input
              name={fieldName}
              id={fieldName}
              value={value}
              aria-label={fieldName}
              onChange={e => setFieldsState(setValue(fieldName, e.target.value))}
              onBlur={_ => setFieldsState(setTouched(fieldName))}
            />
          </div>
        ))
      }
    </form>
  )
}