Giter Site home page Giter Site logo

ndom91 / react-timezone-select Goto Github PK

View Code? Open in Web Editor NEW
203.0 3.0 45.0 5 MB

🌐 An extremely usable and dynamic React timezone selector

Home Page: https://ndom91.github.io/react-timezone-select/

License: MIT License

HTML 12.22% TypeScript 83.01% CSS 4.76%
react timezone select component typescript hacktoberfest

react-timezone-select's Introduction

🌐⌚ react-timezone-select

npm NPM Downloads Skypack Test CI MIT

Another react timezone select component, I know.. However this one has a few key benefits!

While looking around for a good option, I had trouble finding a timezone select components which:

  1. Adjusted the choices automatically with Daylight Savings Time (DST)
  2. Didn't have a huge list of choices to scroll through when technically only 24 (ish) are necessary

Important

This demo is also available in the ./examples directory. Simply run pnpm dev in the root of the repository and the vite dev server will start, where you can then find the example app at localhost:3001.

🏗️ Installing

npm install react-timezone-select react-select

Caution

The package react-select is optional. It is unnecessary if you're only using the hook.

🔭 Usage

import React, { useState } from "react"
import ReactDOM from "react-dom"
import TimezoneSelect, { type ITimezone } from "react-timezone-select"

const App = () => {
  const [selectedTimezone, setSelectedTimezone] = useState<ITimezone>(
    Intl.DateTimeFormat().resolvedOptions().timeZone,
  )

  return (
    <div className="App">
      <h2>react-timezone-select</h2>
      <blockquote>Please make a selection</blockquote>
      <div className="select-wrapper">
        <TimezoneSelect value={selectedTimezone} onChange={setSelectedTimezone} />
      </div>
      <h3>Output:</h3>
      <div
        style={{
          backgroundColor: "#ccc",
          padding: "20px",
          margin: "20px auto",
          borderRadius: "5px",
          maxWidth: "600px",
        }}
      >
        <pre
          style={{
            margin: "0 20px",
            fontWeight: 500,
            fontFamily: "monospace",
          }}
        >
          {JSON.stringify(selectedTimezone, null, 2)}
        </pre>
      </div>
    </div>
  )
}

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

🎨 Timezone Hook

By default, react-timezone-select uses react-select as underlying select component. If you'd like to bring your own select component, you can use the useTimezoneSelect hook instead of the TimezoneSelect component to render the timezones using your self-provided select component.

import { useTimezoneSelect, allTimezones } from "react-timezone-select"

const labelStyle = "original"
const timezones = {
  ...allTimezones,
  "Europe/Berlin": "Frankfurt",
}

const customSelect = () => {
  const { options, parseTimezone } = useTimezoneSelect({ labelStyle, timezones })

  return (
    <select onChange={(e) => onChange(parseTimezone(e.currentTarget.value))}>
      {options.map((option) => (
        <option value={option.value}>{option.label}</option>
      ))}
    </select>
  )
}

🕹️ Props

Prop Type Default Note
value string | ITimezoneOption null Initial/current Timezone
onBlur () => void null
onChange (timezone: ITimezoneOption) => void null
labelStyle 'original' | 'altName' | 'abbrev' | 'offsetHidden' 'original'
displayValue 'GMT' | 'UTC' 'GMT' Prefix for the label (i.e. "(GMT+2:00)" or "(UTC+2:00)")
timezones Record allTimezones
currentDatetime Date | string null Override datetime used to calculate timezone values (alternative to current datetime), useful for calculating different summer / winter times, etc.

Example values:

// string
value='America/Juneau'
// ITimezoneOption; i.e. `onChange` return value
value={{
  value: 'America/Juneau'
  label: '(GMT-8:00) Alaska,
  abbrev: 'AHST',
  offset: -8,
  altName: 'Alaskan Standard Time'
}}

Example timezones:

timezones={{
  ...allTimezones,
  'America/Lima': 'Pittsburgh',
  'Europe/Berlin': 'Frankfurt',
}}

✨ Tips

👤 Default Users Timezone

If you'd like the user's own timezone to be set as the initially selected option on render, we can make use of the new Intl browser API by setting the default state value to Intl.DateTimeFormat().resolvedOptions().timeZone.

const [timezone, setTimezone] = useState(Intl.DateTimeFormat().resolvedOptions().timeZone)

🕒 Custom Timezones

You can append custom choices of your own, or fully replace the listed timezone options.

The timezones prop takes a dictionary of timezones in the format of "{ tzIdentifier: Label }" (Timezone Identifiers).

import TimezoneSelect, { type ITimezone, allTimezones } from 'react-timezone-select'

const [selectedTimezone, setSelectedTimezone] = useState<ITimezone>('Europe/Berlin')

<TimezoneSelect
  value={selectedTimezone}
  onChange={setSelectedTimezone}
  timezones={{
    ...allTimezones,
    'America/Lima': 'Pittsburgh',
    'Europe/Berlin': 'Frankfurt',
  }}
/>

The example above will include all original timezones and generate two additional choices:

  • '(GMT-5:00) Pittsburgh'
  • '(GMT+1:00) Frankfurt'

We'll prepend the correct (GMT...) part to the generated label, you just have to provide the string you want in your label. Also, you can omit spreading in the allTimezones object for a select dropdown consisting of only your custom choices.

🚧 Contributing

Pull requests are always welcome! Please stick to repo formatting/linting settings, and if adding new features, please consider adding test(s) and documentation where appropriate!

🙏 Thanks

📝 License

MIT

react-timezone-select's People

Contributors

averb avatar braingu-matt avatar codeforcesmeme avatar dependabot[bot] avatar dreierf avatar emrysal avatar frecap avatar gflores-jahia avatar gitstart avatar halilim avatar methuselah96 avatar ndom91 avatar nordicdesign avatar nsantos16 avatar salmanorak avatar talyuk avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

react-timezone-select's Issues

question

Hi, this isn't an issue but a question. I am trying to figure out how to style the react-timezone-select - specifically change the color of the background upon selection, the border color on focus and the selected text. The blue doesn't fit my project but my normal styling that I would do isn't working (specifying hover states and specifying border color has no effect). Any advice?

Use a development component instead a build folder

I'm trying to implement the feature requested by Peerrich in calcom (calcom/cal.com#2939), but as the TimezoneSelect component is imported from the build, it makes it difficult to make some kind of change in the code.
In the example folder (example/src/Timezone.tsx), the TimezoneSelect is imported from dist folder
Screenshot from 2022-07-07 10-39-50

As it is, any changes made to the code will not reflect in the development, when we create a .tsx component for TimezoneSelect instead of importing from the build we will be able to see the changes at the same time as we do

Custom Styling CSS

Clear and concise description of the problem

I really appreciate this project but I'm not able to easily change the styling of the elements (with react). Especially for themes that have a light/dark style switch for users that prefer a dark version of a theme.

Suggested solution

I think the best way would be to add props that define the name of the CSS class for the div elements. Thanks guys!

Alternative

No response

Additional context

No response

Validations

  • Check that there isn't already an issue that request the same feature to avoid creating a duplicate.

How to get the initial data

Hi,

I'm getting the below object onChange event.

  {
   value: 'America/Juneau'
   label: '(GMT-8:00) Alaska,
   abbrev: 'AHST',
   offset: -8,
   altName: 'Alaskan Standard Time'
 }

In my case, I load the form with some predefined data and pass the initial timezone value

const [timezone, setTimezone] = useState(Intl.DateTimeFormat().resolvedOptions().timeZone);

// assume we have some other fields here
<TimezoneSelect
      value={timezone}
      onChange={setTimezone}
      menuPosition="absolute"
      menuPlacement="auto"
/>
// assume that we have a submit button here

So, on rendering the form the timezone is preselected with my local timezone. But I didn't get the offset object in timeZone useState, I'm getting those data onChange the TimezoneSelect(react-select).

How to get the initial data with offset without changing the dropdown?

or How to trigger the onChange event?

In your official sample itself, we have that issue. In the code section, it displays "Europe/Rome" without showing the actual object, it only displays on selecting the same value again.

Is that possible to show the selected object value in onLoading?

image

Thanks,
Chandru

Mouse cursor is set to "cursor: default"

Should the styling for the dropdown be changed from

cursor: default

to

cursor: pointer

to better display the intent to the end user that this is an interactive element & also from an accessibility perspective?

Component no longer accepting onChange handler?

Hey Nico,

First off, thanks for taking the time to put this package together. I needed a simple timezone select for a project and this has worked perfectly.

However, just this morning I was doing a dependency audit on my project and noticed that the upgrade from 0.5.1 => 0.6.0 broke the functionality of the component.

If I'm reading the source correctly, when you recently refactored to use hooks and a functional component, you are no longer using the onChange prop being passed in when the component is rendered? I was confused because this change is not reflected in the example.

I see that you are passing through the onBlur prop but this did not work for my implementation.

Just off the top of my head I think it could be possible to create a new callback function inside TimezoneSelect which both calls the props.onChange function passed to the component and also calls the local setSelectedTimezone function. Then you could pass that wrapper as the callback to the Select onChange?

Many thanks again.
Cheers,
Dana

Error: Module parse failed: Unexpected token (22:59)

Issue when i run cmd: npm start

ERROR in ./node_modules/react-timezone-select/dist/index.js 22:59
Module parse failed: Unexpected token (22:59)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders

The version used:

  • "react-timezone-select": "^1.0.5",
  • "react": "^17.0.2",

Webpack config:
{ test: /\.(js|jsx)$/, exclude: [ { test: path.resolve(__dirname, 'node_modules'), }, ], use: { loader: 'babel-loader', }, },

Has anyone had such a situation and solution?
Thanks!

Broken with latest react scripts v5?

Since upgrading to react-scripts v5, the following error is produced:

Module not found: Error: Can't resolve './timezone-list' in '/frontend/node_modules/react-timezone-select/dist'
Did you mean 'timezone-list.js'?
BREAKING CHANGE: The request './timezone-list' failed to resolve only because it was resolved as fully specified
(probably because the origin is strict EcmaScript Module, e. g. a module with javascript mimetype, a '*.mjs' file, or a '*.js' file where the package.json contains '"type": "module"').
The extension in the request is mandatory for it to be fully specified.
Add the extension to the request.

Is anyone else experiencing this issue as well?

Tijuana US and Canada is mapped to America/Dawson timezone

Good day!
To my knowledge, America/Dawson timezone(utc-7) is different from the timezone in Tijuana US and Canada(utc-8).
But in the dropdown, typing either of them results in America/Dawson
In the code i18n object defined in src/index.js , Tijuana, Pacific Time is mapped to America/Dawson timezone which shouldn't be the case.
This is causing problem since there is no way to differentiate between them.
Wanted to bring to your notice if its a bug or the intention here.
Feel free to correct me if I wrong.
Thanks

@emotion/react when it is already loaded.

Hi,

How are you?
We are using this great package, but we notice that when we are working locally we receive this yellow warning message in the console.
We tried to update @emotion libraries but it's not solved the problem.

/node_modules/react-timezone-select/dist/esm/index.js
You are loading @emotion/react when it is already loaded. Running multiple instances may cause problems. This can happen if multiple versions are used, or if multiple builds of the same version are used.

I hope you can assist us with this manner.

Accept `date` prop for date-specific calculation of DST

With the current selector architecture, isDST() is always calculated on the current date. This leads to a scenario where the time zone names and offsets are incorrect if I'm trying to pick the time zone for a date other than today. For example, if I want to set a date of "3rd January 2020" and select Europe/Amsterdam as a time zone, but the current date is the 10th of June 2020, my time zone will show summer time and have an incorrect offset of +2hrs.

This can be trivially solved by passing an optional date, which would allow the DST check to be carried out the date required, as opposed to the current date. I've already got this working on a branch (I think), but if you're interested I'll look into writing some tests and getting it merged back into main.

Type declarations.

I install the latest version of this library, I am using typescript, I am having this error:

Cannot find module './types/timezone' or its corresponding type declaration

You can notice that the folder types do not show up.

package

types

What am I doing wrong?
Thanks!!!!!

Can you set default values?

hello I have a question and it is that I need to set a default value to the selector. Is it possible? example:
image

Module parse failed: Unexpected token

I have recently updated all the packages of my React project. With the updated project it is failed to compile due to the following error.

./node_modules/react-timezone-select/dist/index.js 31:53
Module parse failed: Unexpected token (31:53)
File was processed with these loaders:
 * ./node_modules/react-scripts/node_modules/babel-loader/lib/index.js
You may need an additional loader to handle the result of these loaders.
|       let label = ""; // @ts-expect-error
| 
>       let abbr = now.isDST() ? tzStrings[0].daylight?.abbr : tzStrings[0].standard?.abbr;
|       let altName = now.isDST() ? tzStrings[0].daylight?.name : tzStrings[0].standard?.name;
|       const min = tz.current.offset * 60;

image

Node JS Version - v14.17.3
React Version - 17.0.2
Typescript Version - 4.4.4

Project was created with create-react-app

Asia/Baku offset

Which offset is right for Baku (GMT+5:00) Baku, Tbilisi, Yerevan or (GMT+4:00) ? where do you get this offset?
Screenshot_2021-06-10_19-26-05
Screenshot_2021-06-10_19-35-42

SyntaxError: Unexpected token '.'

Hey I using Next 12.1 with react-timezone-select 1.3.1 . Normally the timezone component works great but on older browsers such as Safari 12.1.2, Mobile Safari 13.0.4, and Samsung Internet 12.0, the component prevents the site from loading. I'm aware I can use dynamic imports to catch errors before importing a module, but I wanted to mention this in case others have traffic from older browsers.
There's not a lot of info coming from the error:

Unhandled Runtime Error:
SyntaxError: Unexpected token '.'

Call Stack
eval
[native code]
./node_modules/react-timezone-select/dist/esm/index.js

Add "extraLabels" from custom cities for each timezone

Clear and concise description of the problem

At the moment we are not able to create custom timezones, so the ideal would be to give the user the option to be able to create custom timezones. We could use all the information from an existing timezone and just change the value to show in the dropdown

Suggested solution

Add an "extraLabels" prop, which proposes to the user to add a customized label to some timezone. The extraLabels prop is empty by default, when a user wants to add some custom content to the dropdown (like a city) just add an object to the extraLabels prop containing the key label (which will be the name of the timezone in the dropdown) and the key tz (which will be the timezone in which the entry will be entered).
For example, if I add this object to extraLabels:

Screenshot_4

The result in the dropdown will be this: https://www.loom.com/share/6b1e7685dec0409d8b436f38c1a70803

Alternative

No response

Additional context

No response

Validations

  • Check that there isn't already an issue that request the same feature to avoid creating a duplicate.

Optional offset field

This might be a basic question but for the ITimezoneOption type, Typescript says the offset field is optional but for all the select options I clicked on, the offset field was there. Is this a mistake? How can I ensure that all select option fields have an offset?

Recommend update of documentation

Very cool product! Thank you for sharing.

One small nit regarding the docs.

Unless I've overlooked something, using selectedTimezone in the below, will not show the selected value:

<TimezoneSelect
   value={selectedTimezone}
    onChange={tz => setSelectedTimezone(tz)}
/>

What's needed here is to add value or some other key from the selectedTimezone object, like so:

<TimezoneSelect
  value={selectedTimezone.value ? selectedTimezone.value : ""}
  onChange={(tz) => setSelectedTimezone(tz)}
/>

While it might seem obvious on how to show that value, the docs are slightly misleading as written and may confuse new users.

Again, nice product! 🌮

Todo: Fix `react-select` typescript props being passed down

Currently just have a few specific props manually defined. Want to pass in the exported prop types from react-select and allow them all automatically.

I've tried importing types of various names and adding them as optional props to my prop types type, but no luck.

Select timezone by value name

Hello! Thanks for the package!

I'm storing only the value from the JSON object in the database. How can I then match the value with a dropdown to preselect the correct timezone?
So for example, I'm storing in the database "America/Detroit" but when I pass it to the value or the defaultInputValue it only shows me the string, not the timezone object.

Thanks!

Europe/London should be used rather than GMT to define British Timezones

Currently, Dublin, Edinburgh, Lisbon, London are all defined using the identifier GMT, this means that the component cannot adjust for British Summer Time (BST) and prevents the use of default values for this timezone as Europe/London is what is generated from Intl.DateTimeFormat().resolvedOptions().timeZone rather than GMT.

In my opinion, GMT should have the value of UTC, keeping GMT as the key. This way GMT can still be kept constant.

How can I set a deffault Value?

Hi! I am trying to set a defaultValue by doing
defaultValue={entity && update? {timeZone:{label: entity.timeZone}} : {}}
And I can see that the value object is changing but I don't see the value selected

Menu Have and unwanted transparency with material components

Hi :)
I am making a form with material UI textfields. The problem is that when I display the list, the list have some kind of transparency and I can see the material textfields through the menu and it looks horrible. Here is a capture of what is going on:

issue

react-timezone-select package not working with react-scripts 4.0.1 & 4.0.3

package.json: dependencies

"dependencies": {
    "@emotion/react": "^11.4.1",
    "@emotion/styled": "^11.3.0",
    "axios": "^0.24.0",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-router-dom": "^5.2.0",
    "react-scripts": "4.0.3",
    "react-timezone-select": "^1.2.0",
    "sass": "^1.49.0",
    "styled-components": "^5.3.1",
    "web-vitals": "^1.0.1"
  },

Error message:

./node_modules/react-timezone-select/dist/esm/index.js 9693:38
Module parse failed: Unexpected token (9693:38)
File was processed with these loaders:
 * ./node_modules/babel-loader/lib/index.js
You may need an additional loader to handle the result of these loaders.
|           r = ts(a[0]);
|     let o = "",
>         s = n.isDST() ? r[0].daylight?.abbr : r[0].standard?.abbr,
|         l = n.isDST() ? r[0].daylight?.name : r[0].standard?.name;
|     const u = 60 * t.current.offset,

I tried this facebook/create-react-app#10518 (comment) but did not work for me

Missing tz's from timezone-soft not handled gracefully

Describe the bug

I'm try to pass the full list of timezones available in the browser in as a custom timezone list, many work, but a handful don't, and those crash trying to access the empty output from calling timezone-soft

The list of missing timezones can be found in the ticket I logged with them: spencermountain/timezone-soft#17

Some fail accessing the .daylight prop and others .standard

image

image

It would be great if this were to be fixed so that you can just pass the full list in and it will work, even if not perfectly.

Thanks very much for your time,

Adam


this is how I generate the list for your testing purposes:

  const timezones = Intl.supportedValuesOf("timeZone");
  const tzObj = timezones.reduce((a, v) => ({ ...a, [v]: v }), {});

Reproduction

pass in an object of timezone keys and values from the browser timezone list

System Info

System:
    OS: macOS 12.5
    CPU: (16) x64 Intel(R) Core(TM) i9-9880H CPU @ 2.30GHz
    Memory: 43.10 MB / 16.00 GB
    Shell: 5.8.1 - /bin/zsh
  Binaries:
    Node: 18.7.0 - ~/.nvm/versions/node/v18.7.0/bin/node
    Yarn: 1.22.19 - ~/Projects/stateful/app/node_modules/.bin/yarn
    npm: 8.15.0 - ~/.nvm/versions/node/v18.7.0/bin/npm
  Browsers:
    Brave Browser: 89.1.22.67
    Chrome: 103.0.5060.134
    Firefox: 101.0
    Safari: 15.6

Used Package Manager

yarn

Validations

  • Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
  • Check that this is a concrete bug. For Q&A, please open a GitHub Discussion instead.
  • The provided reproduction is a minimal reproducible of the bug.

why is -gmt 8 missing from list.

hello Team(react-timezone-select),

I am facing a small issue I don't know why it is missing from the options list. I have installed the latest version (0.9.9) of your react-timezone-select package. I need (-8 GMT) in my list but it's missing. why is it happening.? Can you please help me?

Screenshot 2021-01-13 at 4 16 49 PM

Select CountryAfghanistanÅland IslandsAlbaniaAlgeriaAmerican SamoaAndorraAngolaAnguillaAntarcticaAntigua and BarbudaArgentinaArmeniaArubaAustraliaAustriaAzerbaijanBahamasBahrainBangladeshBarbadosBelarusBelgiumBelizeBeninBermudaBhutanBoliviaBonaire, Sint Eustatius and SabaBosnia and HerzegovinaBotswanaBouvet IslandBrazilBritish Indian Ocean TerritoryBrunei DarussalamBulgariaBurkina FasoBurundiCambodiaCameroonCanadaCape VerdeCayman IslandsCentral African RepublicChadChileChinaChristmas IslandCocos (Keeling) IslandsColombiaComorosCongo, Republic of the (Brazzaville)Congo, the Democratic Republic of the (Kinshasa)Cook IslandsCosta RicaCôte d'Ivoire, Republic ofCroatiaCubaCuraçaoCyprusCzech RepublicDenmarkDjiboutiDominicaDominican RepublicEcuadorEgyptEl SalvadorEquatorial GuineaEritreaEstoniaEthiopiaFalkland Islands (Islas Malvinas)Faroe IslandsFijiFinlandFranceFrench GuianaFrench PolynesiaFrench Southern and Antarctic LandsGabonGambia, TheGeorgiaGermanyGhanaGibraltarGreeceGreenlandGrenadaGuadeloupeGuamGuatemalaGuernseyGuineaGuinea-BissauGuyanaHaitiHeard Island and McDonald IslandsHoly See (Vatican City)HondurasHong KongHungaryIcelandIndiaIndonesiaIran, Islamic Republic ofIraqIrelandIsle of ManIsraelItalyJamaicaJapanJerseyJordanKazakhstanKenyaKiribatiKorea, Democratic People's Republic ofKorea, Republic ofKuwaitKyrgyzstanLaosLatviaLebanonLesothoLiberiaLibyaLiechtensteinLithuaniaLuxembourgMacaoMacedonia, Republic ofMadagascarMalawiMalaysiaMaldivesMaliMaltaMarshall IslandsMartiniqueMauritaniaMauritiusMayotteMexicoMicronesia, Federated States ofMoldovaMonacoMongoliaMontenegroMontserratMoroccoMozambiqueMyanmarNamibiaNauruNepalNetherlandsNew CaledoniaNew ZealandNicaraguaNigerNigeriaNiueNorfolk IslandNorthern Mariana IslandsNorwayOmanPakistanPalauPalestine, State ofPanamaPapua New GuineaParaguayPeruPhilippinesPitcairnPolandPortugalPuerto RicoQatarRéunionRomaniaRussian FederationRwandaSaint BarthélemySaint Helena, Ascension and Tristan da CunhaSaint Kitts and NevisSaint LuciaSaint MartinSaint Pierre and MiquelonSaint Vincent and the GrenadinesSamoaSan MarinoSao Tome and PrincipeSaudi ArabiaSenegalSerbiaSeychellesSierra LeoneSingaporeSint Maarten (Dutch part)SlovakiaSloveniaSolomon IslandsSomaliaSouth AfricaSouth Georgia and South Sandwich IslandsSouth SudanSpainSri LankaSudanSurinameSwazilandSwedenSwitzerlandSyrian Arab RepublicTaiwanTajikistanTanzania, United Republic ofThailandTimor-LesteTogoTokelauTongaTrinidad and TobagoTunisiaTurkeyTurkmenistanTurks and Caicos IslandsTuvaluUgandaUkraineUnited Arab EmiratesUnited KingdomUnited StatesUnited States Minor Outlying IslandsUruguayUzbekistanVanuatuVenezuela, Bolivarian Republic ofVietnamVirgin Islands, BritishVirgin Islands, U.S.Wallis and FutunaWestern SaharaYemenZambiaZimbabwe

Had to use next-transpile-modules to work with Next.js 12 (next@^12.0.2)

Thank you so much for your time on this. I want to mention that I spent quite some time today trying to get this to work with Next.js 12, and I kept running into these two errors:

  1. Cannot find module '/usr/src/app/node_modules/react/jsx-runtime
  2. Module not found: Can't resolve 'react-timezone-select'

The app would work fine without react-timezone-select installed, but as soon as I would install it, one of those two errors would pop up. I tried many different configurations of webpack, babel, next.config.js. Nothing worked until I finally tried adding the fix you mention with next-transpile-modules...

// next.config.js
const withTM = require("next-transpile-modules")(["react-timezone-select"])

module.exports = withTM({
  // ...further Next.js config
})

This is the only thing that worked for me using Next.js 12. If anyone else runs across this problem, maybe this post will be helpful.

package.json:

"next": "^12.0.2",
"next-transpile-modules": "^9.0.0",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-select": "^5.1.0",
"react-timezone-select": "^1.1.13"

Persistent Storage

If the values are stored in a database, then the component will need a way to set the value without the entire JSON object.

The object will change dynamically through time and not select the previously selected value that was in storage.

Recommend option set set to just be value "America/Juneau" instead. Probably would need to do a typeof check to set the value as string if it is a string, or set the value to object.value if it is an object.

RFC: Allow composition of the Select component.

Hi @ndom91, hope you're doing well.

react-select does a lot of it's styling inline, with keys like theme={} and styles={], as you well know. Therefore I think a common pattern people use is to extend the component like so (example from my code):

function Select<
  Option,
  IsMulti extends boolean = false,
  Group extends GroupBase<Option> = GroupBase<Option>
>({ className, ...props }: SelectProps<Option, IsMulti, Group>) {
  return (
    <ReactSelect
      theme={(theme) => ({
        ...theme,
        borderRadius: 2,
        colors: {
          ...theme.colors,
          primary: "var(--brand-color)",

          primary50: "rgba(209 , 213, 219, var(--tw-bg-opacity))",
          primary25: "rgba(244, 245, 246, var(--tw-bg-opacity))",
        },
      })}
      styles={{
        option: (provided, state) => ({
          ...provided,
          color: state.isSelected ? "var(--brand-text-color)" : "black",
          ":active": {
            backgroundColor: state.isSelected ? "" : "var(--brand-color)",
            color: "var(--brand-text-color)",
          },
        }),
      }}
      components={{
        ...components,
        IndicatorSeparator: () => null,
        Input: InputComponent,
      }}
      className={classNames("text-sm shadow-sm", className)}
      {...props}
    />
  );
}

Due to the definition of react-timezone-select, such configuration is quite easily done; just take that entire code, copy it; and create a secondary wrapper TimezoneSelect and done. Except the drawback of this "easy fix" approach is that you now need to make Select changes in two locations. (An alternative fix is to somehow configure it outside of the component and re-use the config, but this in IMO also a little ugly). So this got me thinking.

I wonder what your opinion is to do something like: (pseudocode)

// file: react-timezone-select.js
import Select from "react-select";
const TimezoneSelect = ({
  innerSelect = Select,
  ...
}: Props) => .... (<innerSelect />)

// This would allow in the implementation
import TimezoneSelect from "react-timezone-select";
import Select from "@components/Select";

<TimezoneSelect innerSelect={Select} /* ... */ />

There's a couple of stylistic ways to achieve the same thing, but what do you think?

Cursor didn't show pointer when passing the dropdown

Describe the bug

On preview page when I open the timezones dropdown the cursor doesn't show "pointer"

Reproduction

  1. Create a new event typr 2. Go to preview 3. Try to change the selected timezone

System Info

System:
    OS: Linux 5.15 Ubuntu 20.04.4 LTS (Focal Fossa)
    CPU: (6) x64 AMD Ryzen 5 3500X 6-Core Processor
    Memory: 157.17 MB / 15.57 GB
    Container: Yes
    Shell: 5.8 - /usr/bin/zsh
  Binaries:
    Node: 14.17.0 - ~/.nvm/versions/node/v14.17.0/bin/node
    Yarn: 1.22.18 - ~/.nvm/versions/node/v14.17.0/bin/yarn
    npm: 8.9.0 - ~/.nvm/versions/node/v14.17.0/bin/npm
  Browsers:
    Chrome: 100.0.4896.127
    Firefox: 103.0

Used Package Manager

yarn

Validations

  • Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
  • Check that this is a concrete bug. For Q&A, please open a GitHub Discussion instead.
  • The provided reproduction is a minimal reproducible of the bug.

Filter Timezones by cities

What i tried to do?
.I was trying to filter the timezones by cities, type the name of a city and be rendered in the dropdown the city or the corrersponding timezone, it is possible? I noticed that the library doens't have data besides the timezones.
.I even tried to create a relationship between this library and another that provides the data of the citeis but it was not possible, becausa the "Timezones" prop does not accept anything different from what it already has in it

Example:
.If i type "San Diego" in the input it should suggest the San Diego timezone, the suggestion can be either to render at once the timezone in which the city exists.
This is how it is now:
Screenshot from 2022-06-14 10-21-38
https://user-images.githubusercontent.com/87545086/173698851-637d3fb1-1ce5-4205-bcda-736f09bb1626.mp4

Dont' have any suggestions about the city(the value on input)

Could have a feature to make it possible to put more name options for the same timezone. So it would be possible to filter by city too(if the code wants to show these custom cities)

Dublin timezone code displays as BST

Describe the bug

I'm using react-timezone-select in my project, and it displays the timezone short code for Dublin as BST:

image

However, when I format times using getLocaleString(), it shows the TimeZone for Dublin as GMT+1:

image

Note that London displays as BST and Lisbon displays as WEST.

The thing is, Irish people tend to be a little sensitive about being called "British". We also tend not to like the UK and Ireland being referred to as the "British Isles". We generally informally refer to summer time as IST for Irish Summer Time, however, this is also used for Indian Summer Time. I quite like WEST like Lisbon, but GMT+1 is probably safest.

I'm not sure if this is something controlled from within react-timezone-select, since I haven't found timezone codes withing the GitHub project, so if you can point me at somewhere else this can be fixed, that would be helpful.

Is this really a bug? I'm not certain, but I'm logging as a bug since react-timezone-select is showing a different timezone code to getLocaleString().

Reproduction

To reproduce, select a react-timezone-select and find (GMT+1:00) Dublin (BST) during summer time.

System Info

System:
    OS: Linux 5.17 Pop!_OS 22.04 LTS
    CPU: (8) x64 11th Gen Intel(R) Core(TM) i5-1135G7 @ 2.40GHz
    Memory: 1.40 GB / 15.42 GB
    Container: Yes
    Shell: 5.1.16 - /bin/bash
  Binaries:
    Node: 12.22.9 - /usr/bin/node
    npm: 8.5.1 - /usr/bin/npm
  Browsers:
    Firefox: 103.0

Used Package Manager

npm

Validations

  • Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
  • Check that this is a concrete bug. For Q&A, please open a GitHub Discussion instead.
  • The provided reproduction is a minimal reproducible of the bug.

Asia/Baku time zone change from GMT+5 to GMT+4

Hi,

I'm using react-timezone-select in one of my projects and a user of ours reported an issue with the Asia/Baku - Baku, Tbilisi, Yerevan time zone.
It appears as (GMT+5:00) but it should be (GMT+4:00).

Digging a bit deeper, I realised that they actually literally changed their time zone recently.
The update was reflected in spacetime v6.16.2 https://github.com/spencermountain/spacetime/releases/tag/6.16.2 and respectively in react-timezone-select v1.1.11 2d945cb

So having seen these updates, I thought maybe my project's version was old, but that's not the case:

react-timezone-select@^1.1.13:
  version "1.1.13"
  resolved "https://registry.yarnpkg.com/react-timezone-select/-/react-timezone-select-1.1.13.tgz#76090b9511b14e7dbf9474b30c61bd77a64a1852"
  integrity sha512-lHcjnax3HtLyHCa+yI3xO6IOLfMI4rTjlFGHN2fBauerKi4ee+ZGoQ6zw7HHisTkWmyU4iE/Xf3gSh1pEQMW8g==
  dependencies:
    react-select "^5.0.0"
    spacetime "^6.16.3"
    timezone-soft "^1.3.1"

I'm a bit stumped since it seems that I'm running the latest versions of both react-timezone-select and spacetime underneath and yet the wrong time zone is displayed for Asia/Baku.

Any ideas why that might be?

Thanks,
Iskren

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.