Created
May 9, 2020 08:13
-
-
Save Vultraz/d191add87e29da8f29e26121bf4af24e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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