Last active
November 25, 2024 14:27
-
-
Save everdimension/a5c1e991a8a6b6aab060ce349b37b825 to your computer and use it in GitHub Desktop.
React Input element with support for customValidity props
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
/** | |
* Usage: | |
* <Input customValidity="your validation message" /> // add constraint | |
* or | |
* <Input customValidity="" /> // remove constraint | |
* or | |
* <Input defaultCustomValidity="you message" /> // initial validationMessage | |
*/ | |
export function Input({ | |
defaultCustomValidity, | |
customValidity, | |
...props | |
}: React.InputHTMLAttributes<HTMLInputElement> & { | |
defaultCustomValidity?: string; | |
customValidity?: string; | |
}) { | |
const ref = useRef<HTMLInputElement | null>(null); | |
// 1. "Controlled" case | |
useEffect(() => { | |
const input = ref.current; | |
if (customValidity != null && input) { | |
input.setCustomValidity(customValidity); | |
} | |
}, [customValidity]); | |
// 2. "Uncontrolled" case | |
const customValidityRef = useRef(defaultCustomValidity); | |
useEffect(() => { | |
const input = ref.current; | |
if (customValidityRef.current && input) { | |
input.setCustomValidity(customValidityRef.current); | |
} | |
}, []); | |
return <input ref={ref} {...props} />; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment