Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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