Skip to content

Instantly share code, notes, and snippets.

@jucian0
Last active March 8, 2020 13:10
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 jucian0/ffa9e9b39eaac7fda5ef57ad393d2ff4 to your computer and use it in GitHub Desktop.
Save jucian0/ffa9e9b39eaac7fda5ef57ad393d2ff4 to your computer and use it in GitHub Desktop.
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