Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Documentation FR: Actual usage in a front-end select component #283

Open
timfee opened this issue Mar 22, 2023 · 0 comments
Open

Documentation FR: Actual usage in a front-end select component #283

timfee opened this issue Mar 22, 2023 · 0 comments

Comments

@timfee
Copy link

timfee commented Mar 22, 2023

I ended up writing this wrapper to present a nice dropdown list:

// util/timezones.ts
import { rawTimeZones } from "@vvo/tzdb"

export type TimeZoneData = {
  /**
   * A map of display strings to time zone data. The key is a formatted string
   * that represents the time zone offset and alternative name (e.g.,
   * "(GMT+02:00) Central European Time"), and the value is an object containing
   * the IANA time zone name (e.g., "Europe/Berlin") and an array of associated
   * group names.
   */
  timeZoneMap: Map<string, { value: string; group: string[] }>
  /**
   * A map of group names to IANA time zone names. The key is the group name
   * (e.g., "US/Central"), and the value is the corresponding IANA time zone
   * name (e.g., "America/Chicago").
   */
  groupLookupMap: Map<string, string>
}
/**
 * Generates a manageable amount of of display strings (<200) in
 * {@link timeZoneMap}, as well as a {@link groupLookupMap} so we can
 * process any timezone to its corresponding value in the UI.
 */
function getTimezoneData(): TimeZoneData {
  const timeZoneMap = new Map<string, { value: string; group: string[] }>()
  const groupLookupMap = new Map<string, string>()

  // Iterate through the rawTimeZones array
  for (const { rawFormat, name, group } of rawTimeZones) {
    // Add the display string to timeZoneMap if it doesn't exist
    if (!timeZoneMap.has(rawFormat)) {
      timeZoneMap.set(rawFormat, {
        value: name,
        group,
      })
    }

    // Add the time zone name to groupLookupMap for each group in rawTimeZone.group
    for (const tz of group) {
      if (!groupLookupMap.has(tz)) {
        groupLookupMap.set(tz, name)
      }
    }
  }

  return { timeZoneMap, groupLookupMap }
}

export default getTimezoneData

And created a React component that shows a dropdown:

// components/TimeZonePicker.tsx
const { groupLookupMap, timeZoneMap } = getTimezoneData()

export default function TimezonePicker() {
  const {
    state: { timeZone },
    dispatch,
  } = useProvider()

  // ⭐️ The relevant bit here; how to handle a TZ (e.g. Intl.DateTimeFormat().resolvedOptions)
  // that may not have been chosen as the value for that specific locale.
  //
  const selectedTimeZoneValue = groupLookupMap.get(timeZone)

  return (
    <div className="flex-grow">
      <label
        htmlFor="location"
        className="block text-sm font-medium leading-0 text-gray-900">
        Timezone
      </label>

      <select
        value={selectedTimeZoneValue}
        id="location"
        name="location"
        className="mt-1 block w-full rounded-md border-0 py-1.5 pl-3 pr-10 text-gray-900 ring-1 ring-inset ring-gray-300 focus:ring-2 focus:ring-accent-600 sm:text-sm sm:leading-6"
        onChange={(e) => {
          dispatch({
            type: "SET_TIMEZONE",
            payload: e.currentTarget.value,
          })
        }}>
        {[...timeZoneMap].map(([display, { value }]) => (
          <option key={display} value={value}>
            {`GMT${display}`}
          </option>
        ))}
      </select>
    </div>
  )
}

When I set up my state (or in my case reducer), I pass it

  const timeZone =
    values.timeZone ?? Intl.DateTimeFormat().resolvedOptions().timeZone ?? "UTC"

Not sure if this approach might be helpful to include in the docs, but figured I'd at least immortalize it here since it's something that I've been working on :)

Screen Shot 2023-03-22 at 12 16 52 2

Thanks for the library, @vvo 👏🏼

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant