spoiler
import React, { useState } from 'react';
import { createSelector } from 'reselect';
import { connect } from 'react-redux';
import './CustomInput.css';
import { RootState } from '../common/root-reduser';
interface CustomInputProps {
name: string;
type: string;
label: string | null;
placeholder: string;
value: string;
onChange: (data: CallbackCustomInputData) => void;
isClear?: boolean;
}
export interface CallbackCustomInputData {
name: string;
value: string;
}
const clearSelector = (state: RootState) => state.user.isClear;
const getClear = createSelector(clearSelector, (i) => i);
const CustomInput: React.FC = (props: CustomInputProps) => {
const [checked, setChecked] = useState(false);
const handleKeyDown = (event: React.KeyboardEvent) => {
const { key } = event;
if (key === ' ' || key === 'Enter') {
setChecked(!checked);
}
};
return (
htmlFor={`${props.type}-${props.label}`}
className={
props.type === 'checkbox'
? 'wrapper-input__label-checkbox'
: 'wrapper-input__label-custom'
}
>
{props.label}
{props.type !== 'checkbox' ? (
name={props.name}
className="wrapper-input__custom-input"
id={`${props.type}-${props.label}`}
type={props.type}
placeholder={props.placeholder}
value={props.isClear && props.value}
defaultValue={props.value}
onChange={(event: React.ChangeEvent) =>
props.onChange({ name: props.name, value: event.currentTarget.value })
}
/>
) : (
role="checkbox"
aria-checked={checked}
aria-labelledby={`${props.type}-${props.label}`}
tabIndex={0}
className={`square outline icon column__icon ${checked ? 'check' : ``}`}
onClick={() => setChecked(!checked)}
onKeyDown={handleKeyDown}
/>
name={props.name}
className="wrapper-input__custom-input"
id={`${props.type}-${props.label}`}
type={props.type}
placeholder={props.placeholder}
checked={checked}
onChange={() => setChecked(!checked)}
/>
)}
);
};
CustomInput.defaultProps = {
isClear: undefined,
};
export default connect((state: RootState) => {
return {
isClear: getClear(state),
};
}, null)(CustomInput);