vixnguyen / timezone-select

10 stars 2 forks source link

Timezone Select JS

Demo here

There are excellent benefits competitive to others:

Install

npm i timezone-select-js

Built-in

Methods

clientTz

Components (React only)

TimezoneSelect

Look at the example of usage below

Usage

React

import { listTz, clientTz, findTzByName } from 'timezone-select-js';
import React, { useMemo } from 'react';
import Select from 'react-select';

const TimezoneSelect = ({
  value,
  onBlur,
  onChange,
  labelStyle = 'original',
  ...props
}) => {

  const getOptions = useMemo(() => {
    return listTz();
  }, [labelStyle]);

  const handleChange = tz => {
    onChange && onChange(tz);
  };

  const constructTz = (data) => {
    return typeof data === 'string' ? findTzByName(data, getOptions) : data;
  };

  return (
    <Select
      value={constructTz(value)}
      onChange={handleChange}
      options={getOptions}
      onBlur={onBlur}
      {...props}
    />
  )
}

const App = () => {
  const [selectedTimezone, setSelectedTimezone] = useState(clientTz());
  return (
    <div className='app'>
      <h2>Timezone Select</h2>
      <blockquote>Please make a selection</blockquote>
      <div>
        <TimezoneSelect
          value={selectedTimezone}
          onChange={setSelectedTimezone}
        />
      </div>
    </div>
  )
}

const rootElement = document.getElementById('root')
ReactDOM.render(<App />, rootElement)

Angular

import { listTz, clientTz } from 'timezone-select-js';
import {NgSelectModule, NgOption} from '@ng-select/ng-select';

@Component({...})
export class ExampleComponent {

  timezones = listTz();
  selectedTimezone = clientTz();

}
<!--Using ng-option and for loop-->
<ng-select [(ngModel)]="selectedTimezone">
   <ng-option *ngFor="let tz of timezones" [value]="tz.value">{{tz.label}}</ng-option>
</ng-select>

<!--Or using items input-->
<ng-select [items]="timezones" 
           bindLabel="label" 
           bindValue="value" 
           [(ngModel)]="selectedTimezone">
</ng-select>

VueJS

import { listTz, clientTz } from 'timezone-select-js';

new Vue({
  el: '...',
  template: '...',
  data: {
    selected: clientTz(),
    timezones: listTz();
  }
})
<select v-model="selected">
  <option v-for="tz in timezones" :selected="selected === tz.value" v-bind:value="tz.value">{{ tz.label }}</option>
</select>

Contributing

Pull requests are always welcome!