Last active
May 22, 2019 16:41
-
-
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)
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
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