Last active
March 8, 2020 13:10
-
-
Save jucian0/ffa9e9b39eaac7fda5ef57ad393d2ff4 to your computer and use it in GitHub Desktop.
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, { useState, useRef, useEffect, useCallback } from 'react'; | |
import { debounce } from '../Debounce'; | |
const Input = ({ error, label, onChange, ...rest }) => { | |
const [touched, setTouched] = useState(false) | |
const inputRef = useRef(null) | |
const debounceInput = useCallback(debounce(onChange, 500), [debounce]) | |
const blurInput = useCallback(() => setTouched(true), [setTouched]) | |
useEffect(() => { | |
inputRef.current.addEventListener('input', debounceInput) | |
inputRef.current.addEventListener('blur', blurInput) | |
}, [blurInput, debounceInput, inputRef]) | |
return ( | |
<> | |
<label htmlFor={rest.name}>{label}</label> | |
<input className="form-control" {...rest} ref={inputRef} /> | |
<span className="text-danger">{touched && error}</span> | |
</> | |
); | |
} | |
export default Input | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment