Last active
April 27, 2020 06:49
-
-
Save hallettj/abc251ad3131e9652692b5dfdf1e6030 to your computer and use it in GitHub Desktop.
Custom timezone-aware datetime input component for Sanity CMS
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
import styles from "part:@sanity/base/theme/forms/text-input-style" | |
import FormField from "part:@sanity/components/formfields/default" | |
import { withDocument } from "part:@sanity/form-builder" | |
import PatchEvent, { set, unset } from "part:@sanity/form-builder/patch-event" | |
import * as React from "react" | |
import Datetime from "react-datetime" | |
class DatetimeInputRaw extends React.Component { | |
render() { | |
// `document` is the event we are editing | |
const { document, markers, readOnly, type, value } = this.props | |
// Reference the location entered for the event (if one has been selected) | |
// to get it's time zone. | |
const timezone = document.location?.tz ?? FALLBACK_TZ | |
const selectedDatetime = value && new Date(value) | |
return ( | |
<FormField | |
label={type.title} | |
description={type.description} | |
markers={markers} | |
> | |
<Datetime | |
value={selectedDatetime} | |
displayTimeZone={timezone} | |
onChange={(datetime) => this.onSelectDate(datetime)} | |
inputProps={{ className: styles.textInput, disabled: readOnly }} | |
/> | |
</FormField> | |
) | |
} | |
private onSelectDate(date: Date | null) { | |
const patch = PatchEvent.from(date ? set(date.toISOString()) : unset()) | |
this.props.onChange(patch) | |
} | |
} | |
// Wrap `DatetimeInputRaw` with the `withDocument` higher-order component to | |
// inject the `document` prop. | |
export const DatetimeInput: React.ComponentType<DatetimeInputProps> = withDocument( | |
DatetimeInputRaw | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment