I have an application written in React Typescript with hooks where I am trying to set a date input field in two ways(controlled/uncontrolled). It should change either when the user changes the input or when the component receives props from its parent.
However, my problem is that after I set the value prop at the input-field, it is not possible for the user to change the values in the input-field... Here is my code:
interface Props {
valuesChanged: (type: string, value: string) => void;
minChanged: string;
maxChanged: string;
}
const DateInputField: FC<Props> = ({ valuesChanged, minChanged, maxChanged }: Props) => {
const [minValue, setMinValue] = useState<string>('');
const [maxValue, setMaxValue] = useState<string>('');
// Input changed in parent, trigger changes here
useEffect(() => {
const date = moment(minChanged, 'YYYY-MM-DD', true);
if (date.isValid()) {
setMinValue(minChanged);
}
}, [minChanged]);
useEffect(() => {
const date = moment(maxChanged, 'YYYY-MM-DD', true);
if (date.isValid()) {
setMaxValue(maxChanged);
}
}, [maxChanged]);
// Input changed in input field
const inputChanged = (type: string, input: string) => {
const date = moment(input, 'YYYY-MM-DD', true);
if (date.isValid()) {
valuesChanged(type, input); // tell parent component values changed
if (type === 'startDate') {
setMinValue(input);
} else if (type === 'endDate') {
setMaxValue(input);
}
}
};
return (
<div>
<input value={maxValue} type="date" onChange={(e) => inputChanged('endDate', e.target.value)} />
<input value={maxValue} type="date" onChange={(e) => inputChanged('endDate', e.target.value)} />
</div>
);
};
export default DateInputField;
The valuesChanged prop is a function telling the parent that values in this component changed. Hope someone can help!