Skip to content

Instantly share code, notes, and snippets.

@joemaffei
Last active May 22, 2019 16:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joemaffei/39ce50f4576370e3a6b75cfb41b87d39 to your computer and use it in GitHub Desktop.
Save joemaffei/39ce50f4576370e3a6b75cfb41b87d39 to your computer and use it in GitHub Desktop.
React hook for active validation (e.g. on change of a controlled input)
import React, { useEffect, useState } from 'react';
function useActiveValidation(value, validator) {
const [isValid, setIsValid] = useState(true);
useEffect(() => {
setIsValid(validator(value));
}, [value]);
return isValid;
}
function Example() {
const [inputValue, setInputValue] = useState('');
const validIfNotEmpty = useActiveValidation(inputValue, x => !!x);
function handleChange(e) {
setInputValue(e.target.value);
}
return (
<div>
<input onChange={handleChange) value={inputValue} />
<br />
{validIfNotEmpty ? 'valid' : 'not valid'}
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment