Skip to content

Instantly share code, notes, and snippets.

@Vultraz
Created May 9, 2020 08:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Vultraz/d191add87e29da8f29e26121bf4af24e to your computer and use it in GitHub Desktop.
Save Vultraz/d191add87e29da8f29e26121bf4af24e to your computer and use it in GitHub Desktop.
export const TextDayPicker = forwardRef(
({ date = '', onChange, format: displayFormat = 'Do MMMM YYYY', ...props }, ref) => {
const formatDate = newDate => (newDate ? format(newDate, displayFormat) : '');
const [isEditing, setIsEditing] = useState(false);
const [value, setValue] = useState({
raw: date,
formatted: formatDate(date),
});
useEffect(() => {
onChange(value.raw);
}, [value.raw]);
const onFocus = () => {
setIsEditing(true);
};
const onBlur = () => {
setIsEditing(false);
// Parse the raw input. This may be a string such as 'Today'.
const parsedDate = chrono.parseDate(value.raw);
// If valid, convert it to ISO 8601.
const newDate = parsedDate ? format(parsedDate, 'YYYY-MM-DD') : null;
setValue({
raw: newDate,
formatted: formatDate(newDate),
});
};
const handleChange = ({ target: { value: raw } }) => {
setValue(oldValue => ({ ...oldValue, raw }));
};
return (
<Input
ref={ref}
value={isEditing ? value.raw : value.formatted}
placeholder="Enter a date..."
onFocus={onFocus}
onBlur={onBlur}
onChange={handleChange}
{...props}
/>
);
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment