Skip to content

Instantly share code, notes, and snippets.

@marlosirapuan
Created July 9, 2020 11:54
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 marlosirapuan/ce8e573265980fd237c5c91086f44120 to your computer and use it in GitHub Desktop.
Save marlosirapuan/ce8e573265980fd237c5c91086f44120 to your computer and use it in GitHub Desktop.
React custom Input
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