Last active
May 22, 2019 16:43
-
-
Save joemaffei/3745b92feafc96a974e5ca06075408e7 to your computer and use it in GitHub Desktop.
React hook for passive validation (e.g. on form submit)
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 usePassiveValidation(value, validator) { | |
const [valid, setValid] = useState(true); | |
const [checkValue, setCheckValue] = useState(null); | |
const [didMount, setDidMount] = useState(false); | |
function validate() { | |
setCheckValue(value); | |
return validator(value); | |
} | |
useEffect(() => { | |
setDidMount(true); | |
}, []); | |
useEffect(() => { | |
setValid(true); | |
}, [value]); | |
useEffect(() => { | |
if (didMount) setValid(validator(checkValue)); | |
}, [checkValue]); | |
return [ valid, validate ]; | |
} | |
function Example() { | |
const [inputValue, setInputValue] = useState(''); | |
const [validIfNotEmpty, validateInput] = usePassiveValidation(inputValue, x => !!x); | |
function handleChange(e) { | |
setInputValue(e.target.value); | |
} | |
return ( | |
<div> | |
<input onChange={handleChange) value={inputValue} /> | |
<br /> | |
{validIfNotEmpty ? 'valid' : 'not valid'} | |
<br /> | |
<button onClick={validateInput}>validate</button> | |
</div> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment