Created
December 23, 2020 14:46
-
-
Save DarkoTrpevski/610b704c6c8df7cc416bc0a3f21c078c to your computer and use it in GitHub Desktop.
React useForm hook v3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export interface FormInput { | |
value: any; | |
onChange: any; | |
error: string; | |
} | |
export interface FormError { | |
[key: string]: string; | |
} | |
export interface ValidationOption { | |
required?: string; | |
validateUsing?: ValidationFunc | ValidationFunc[]; | |
} | |
export type ValidationFunc = (value: any) => string; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useState } from "react"; | |
import { FormError, ValidationOption } from "./types"; | |
const useForm = () => { | |
const [errors, setErrors] = useState<FormError>({}); | |
const [isValid, setIsValid] = useState<boolean>(true); | |
const [isPristine, setIsPristine] = useState(true); | |
const updateFormInput = (name: string, error: string) => { | |
let newErrors = {...errors}; | |
if (error) { | |
newErrors[name] = error | |
} else { | |
delete newErrors[name]; | |
} | |
setIsPristine(false); | |
setErrors(newErrors); | |
setIsValid(Object.keys(newErrors).length === 0); | |
} | |
const clearErrors = () => setErrors({}); | |
const useFormInput = (name: string, initialValue?: any, validationOption: ValidationOption = {}) => { | |
const [value, setValue] = useState(initialValue); | |
const onChange = (e:any) => { | |
setValue(e.target.value); | |
updateFormInput(name, getError(validationOption, e.target.value)); | |
} | |
const setError = (err: string) => { | |
updateFormInput(name, err); | |
} | |
return {name, value, setValue, onChange, error: errors[name], setError} | |
} | |
return {isValid, isPristine, errors, useFormInput, clearErrors, setErrors}; | |
} | |
const getError = (validationOption: ValidationOption, val: any): string => { | |
let err = '' | |
if (validationOption) { | |
if (validationOption.required && !val) { | |
err = validationOption.required; | |
} else if (validationOption.validateUsing) { | |
if (Array.isArray(validationOption.validateUsing)) { | |
for (const validator of validationOption.validateUsing){ | |
err = validator(val); | |
if (err){ | |
return err; | |
} | |
} | |
} else if (typeof validationOption.validateUsing === 'function'){ | |
err = validationOption.validateUsing(val); | |
} | |
} | |
} | |
return err; | |
} | |
export default useForm; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment