Skip to content

Instantly share code, notes, and snippets.

@everdimension
Last active November 25, 2024 14:27
Show Gist options
  • Save everdimension/a5c1e991a8a6b6aab060ce349b37b825 to your computer and use it in GitHub Desktop.
Save everdimension/a5c1e991a8a6b6aab060ce349b37b825 to your computer and use it in GitHub Desktop.
React Input element with support for customValidity props
/**
* 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