Untitled
unknown
javascript
3 years ago
2.4 kB
7
Indexable
import { useState } from 'react';
import { Controller } from 'react-hook-form';
import { Typography } from 'antd';
import { get } from 'lodash';
import * as Styled from './styled';
import type { FunctionComponent, ChangeEventHandler } from 'react';
import type {
Control,
FieldValues,
ControllerRenderProps,
ControllerFieldState,
} from 'react-hook-form';
const { Text } = Typography;
const Input: FunctionComponent<{
name: string;
controlType: 'normal' | 'useControl';
size?: 'small' | 'medium' | 'large';
placeholder?: string;
disabled?: boolean;
useVisibilityToggle?: boolean;
control?: Control<App.Any, App.Any>;
value?: string;
onChange?: ChangeEventHandler<HTMLInputElement>;
// eslint-disable-next-line max-lines-per-function
}> = ({
name,
controlType,
size = 'medium',
useVisibilityToggle = true,
placeholder,
disabled,
control,
value,
onChange,
}) => {
const [inputValueVisible, setInputValueVisible] = useState<boolean>(true);
const getIconRenderProps = (useVisibilityToggle: boolean) => {
const props: {
iconRender?: (visible: boolean) => React.ReactNode;
} = {};
if (!useVisibilityToggle) {
props.iconRender = (_) => null;
}
return props;
};
const renderInputField = (
fieldProps?: ControllerRenderProps<FieldValues, string>,
fieldState?: ControllerFieldState,
) => (
<Styled.Input
size={size === 'medium' ? 'middle' : size}
status={!!get(fieldState, 'error') && 'error'}
disabled={disabled}
placeholder={placeholder}
visibilityToggle={{
visible: inputValueVisible,
onVisibleChange: setInputValueVisible,
}}
value={value}
onChange={onChange}
{...fieldProps}
{...getIconRenderProps(useVisibilityToggle)}
/>
);
const renderComponent = (): JSX.Element => {
if (controlType === 'normal') {
return renderInputField();
}
return (
<Controller
name={name}
control={control}
defaultValue={value}
render={({ field, fieldState }) => (
<>
{renderInputField(field, fieldState)}
{!!get(fieldState, 'error') && (
<Text type="danger">{!!get(fieldState, 'error.message')}</Text>
)}
</>
)}
/>
);
};
return <>{renderComponent()}</>;
};
export default Input;
Editor is loading...