Last active
February 16, 2021 17:51
-
-
Save Daniel-Vinicius/4ed3ebf1789802da315eae3fc8b141fb 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, { | |
InputHTMLAttributes, | |
useEffect, | |
useRef, | |
useState, | |
useCallback, | |
} from 'react'; | |
import { IconBaseProps } from 'react-icons'; | |
import { FiAlertCircle } from 'react-icons/fi'; | |
import { useField } from '@unform/core'; | |
import { Container, Error } from './styles'; | |
interface InputProps extends InputHTMLAttributes<HTMLInputElement> { | |
name: string; | |
icon?: React.ComponentType<IconBaseProps>; | |
} | |
const Input: React.FC<InputProps> = ({ name, icon: Icon, ...rest }) => { | |
const inputRef = useRef<HTMLInputElement>(null); | |
const [isFocused, setIsFocused] = useState(false); | |
const [isFilled, setIsFilled] = useState(false); | |
// useField é um hook do unform que recebe basicamente o nome do campo, e retorna várias propriedades | |
// Quando se utiliza o Unform é nescessário dizer a ele quais campos monitorar. https://unform.dev/api/use-field | |
const { fieldName, defaultValue, error, registerField } = useField(name); | |
// Função dentro de função fica recriando e piora performace, use useCallback | |
const handleInputBlur = useCallback(() => { | |
setIsFocused(false); | |
setIsFilled(!!inputRef.current?.value); | |
}, []); | |
// Função dentro de função fica recriando e piora performace, use useCallback | |
const handleInputFocus = useCallback(() => { | |
setIsFocused(true); | |
}, []); | |
useEffect(() => { | |
// registerField é o método usado para registrar um campo no Unform. | |
registerField({ | |
name: fieldName, | |
ref: inputRef.current, | |
path: 'value', | |
}); | |
}, [fieldName, registerField]); | |
return ( | |
<Container isErrored={!!error} isFocused={isFocused} isFilled={isFilled}> | |
{Icon && <Icon size={20} />} | |
<input | |
onFocus={handleInputFocus} | |
onBlur={handleInputBlur} | |
defaultValue={defaultValue} | |
ref={inputRef} | |
{...rest} | |
/> | |
{error && ( | |
<Error title={error}> | |
<FiAlertCircle color="#c53030" size={20} /> | |
</Error> | |
)} | |
</Container> | |
); | |
}; | |
export default Input; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment