Created
March 2, 2023 09:19
-
-
Save honungsburk/67de87842e9b6bc2515daa01fc8fe53b to your computer and use it in GitHub Desktop.
A react hook that provides helper functions and properties to use in a form input
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 React from "react"; | |
/** | |
* A hook that provides helper functions and properties to use in a form input | |
* | |
* @param initalValue - The initial value of the form input | |
* @param validate - A function that validates the value of the form input | |
* @returns an object with helper functions and properties to use in a form input | |
* | |
*/ | |
function useFormControl<A>( | |
initalValue: A, | |
validate?: (value: A) => string | undefined | |
) { | |
const [value, setValue] = React.useState<A>(initalValue); | |
const [isDirty, setDirty] = React.useState<boolean>(false); | |
return { | |
value, | |
isDirty, | |
isInvalid: isDirty && validate?.(value) !== undefined, | |
error: validate?.(value), | |
setValue: (value: A) => { | |
setValue(value); | |
setDirty(true); | |
}, | |
reset: () => { | |
setValue(initalValue); | |
setDirty(false); | |
}, | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment