Created
August 31, 2019 23:48
-
-
Save intelliapps-io/0bbd6555e8c95e4f05c65353e9280953 to your computer and use it in GitHub Desktop.
React Hook for Forms
This file contains hidden or 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"; | |
export interface UseFormMethods<FormFields> { | |
setFieldValue: (key: keyof FormFields, value: any) => void; | |
setFieldsValue: (values: FormFields) => void; | |
getFieldValue: (key: keyof FormFields) => any; | |
fieldsValue: FormFields; | |
clearForm: () => void | |
} | |
export function useForm<FormFields extends { [key: string]: any }>( | |
initalValues: FormFields, | |
onChange?: (values: FormFields) => void | |
): UseFormMethods<FormFields> { | |
const [values, setValues] = useState<FormFields>(initalValues); | |
const setFieldValue = (key: keyof FormFields, value: any) => { | |
setValues({ | |
...values, | |
[key]: value | |
}); | |
if (onChange) onChange(values) | |
} | |
const setFieldsValue = (values: FormFields) => { | |
setValues(values); | |
if (onChange) onChange(values) | |
} | |
const getFieldValue = (key: keyof FormFields) => values[key]; | |
return { | |
getFieldValue, | |
setFieldValue, | |
fieldsValue: values, | |
setFieldsValue: (values: FormFields) => setFieldsValue(values), | |
clearForm: () => setFieldsValue(initalValues) | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment