Created
July 9, 2020 11:54
-
-
Save marlosirapuan/ce8e573265980fd237c5c91086f44120 to your computer and use it in GitHub Desktop.
React custom 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, { | |
useState, | |
useCallback, | |
forwardRef, | |
DetailedHTMLProps, | |
InputHTMLAttributes, | |
Ref, | |
useRef | |
} from 'react' | |
import { Container } from './styles' | |
interface InputProps | |
extends DetailedHTMLProps< | |
InputHTMLAttributes<HTMLInputElement>, | |
HTMLInputElement | |
> { | |
name: string | |
containerStyle?: object | |
} | |
const Input = ( | |
{ containerStyle, ...props }: InputProps, | |
ref: Ref<HTMLInputElement> | |
): JSX.Element => { | |
const inputRef = useRef<HTMLInputElement>(null) | |
const [isFocused, setIsFocused] = useState(false) | |
const [isFilled, setIsFilled] = useState(false) | |
const handleInputBlur = useCallback(() => { | |
setIsFocused(false) | |
setIsFilled(!!inputRef.current?.value) | |
}, []) | |
const handleInputFocus = useCallback(() => setIsFocused(true), []) | |
return ( | |
<Container style={containerStyle} isFocused={isFocused} isFilled={isFilled}> | |
<input | |
onFocus={handleInputFocus} | |
onBlur={handleInputBlur} | |
ref={ref} | |
{...props} | |
/> | |
</Container> | |
) | |
} | |
export default forwardRef<HTMLInputElement, InputProps>(Input) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment