diff --git a/components/common/CharLimitedFieldset/index.tsx b/components/common/CharLimitedFieldset/index.tsx index 16cbef3e..d3aa498c 100644 --- a/components/common/CharLimitedFieldset/index.tsx +++ b/components/common/CharLimitedFieldset/index.tsx @@ -1,7 +1,14 @@ -import React, { useEffect, useState } from 'react' +import React, { + ForwardRefRenderFunction, + forwardRef, + useEffect, + useState, +} from 'react' + +import classNames from 'classnames' import './index.scss' -interface Props { +interface Props extends React.HTMLProps { fieldName: string placeholder: string value?: string @@ -11,47 +18,61 @@ interface Props { onChange?: (event: React.ChangeEvent) => void } -const CharLimitedFieldset = React.forwardRef( - function useFieldSet(props, ref) { - const fieldType = ['password', 'confirm_password'].includes(props.fieldName) - ? 'password' - : 'text' +const CharLimitedFieldset: ForwardRefRenderFunction = ( + { + fieldName, + placeholder, + value, + limit, + error, + onBlur, + onChange: onInputChange, + ...props + }, + ref +) => { + // States + const [currentCount, setCurrentCount] = useState( + () => limit - (value || '').length + ) - const [currentCount, setCurrentCount] = useState(0) + // Hooks + useEffect(() => { + setCurrentCount(limit - (value || '').length) + }, [limit, value]) - useEffect(() => { - setCurrentCount( - props.value ? props.limit - props.value.length : props.limit - ) - }, [props.limit, props.value]) - - function onChange(event: React.ChangeEvent) { - setCurrentCount(props.limit - event.currentTarget.value.length) - if (props.onChange) props.onChange(event) + // Event handlers + const handleInputChange = (event: React.ChangeEvent) => { + const { value: inputValue } = event.currentTarget + setCurrentCount(limit - inputValue.length) + if (onInputChange) { + onInputChange(event) } - - return ( -
-
- - {currentCount} -
- {props.error.length > 0 &&

{props.error}

} -
- ) } -) -export default CharLimitedFieldset + // Rendering methods + return ( +
+
+ + {currentCount} +
+ {error.length > 0 &&

{error}

} +
+ ) +} + +export default forwardRef(CharLimitedFieldset)