Repository: TronNatthakorn/react-native-wheel-pick Branch: master Commit: fa18934cb78b Files: 21 Total size: 55.6 KB Directory structure: gitextract_azbk_dy6/ ├── .github/ │ └── FUNDING.yml ├── .gitignore ├── LICENSE ├── NOTICE ├── README.md ├── android/ │ ├── build.gradle │ └── src/ │ └── main/ │ ├── AndroidManifest.xml │ └── java/ │ └── com/ │ └── tron/ │ ├── ReactNativeWheelPickerPackage.java │ ├── ReactWheelCurvedPicker.java │ └── ReactWheelCurvedPickerManager.java ├── package.json ├── react-native.config.js └── src/ ├── WheelCurvedPicker.android.js ├── WheelCurvedPicker.ios.js ├── WheelCurvedPicker.web.js ├── date-picker.android.js ├── date-picker.ios.js ├── date-picker.web.js ├── index.d.ts ├── index.js └── picker.js ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/FUNDING.yml ================================================ # These are supported funding model platforms github: TronNatthakorn #patreon: # Replace with a single Patreon username #open_collective: # Replace with a single Open Collective username #ko_fi: # Replace with a single Ko-fi username #tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel #community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry #liberapay: # Replace with a single Liberapay username #issuehunt: # Replace with a single IssueHunt username #lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry #polar: # Replace with a single Polar username #buy_me_a_coffee: # Replace with a single Buy Me a Coffee username #thanks_dev: # Replace with a single thanks.dev username #custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] ================================================ FILE: .gitignore ================================================ android/.gradle android/.idea android/.project android/.settings android/android.iml android/gradle android/gradlew android/gradlew.bat android/local.properties ================================================ FILE: LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: NOTICE ================================================ react-native-wheel-pick Copyright 2022 tron.natthakorn@engineer.com This project contains code copied from AigeStudio: https://github.com/AigeStudio/WheelPicker Copyright 2015-2017 AigeStudio Licensed under the Apache License, Version 2.0 This project contains code copied from @leslisam/react-native-wheel-picker: https://github.com/lesliesam/react-native-wheel-picker This project contains code copied from @wusuopu/react-native-wheel-picker: https://github.com/wusuopu/react-native-wheel-picker This project contains code copied from @pinguinjkeke/react-native-wheel-datepicker: https://github.com/pinguinjkeke/react-native-wheel-datepicker ================================================ FILE: README.md ================================================ # [react-native-wheel-pick](https://www.npmjs.com/package/react-native-wheel-pick) React native wheel picker for both iOS and android. This is not original but inspired by [react-native-wheel-datepicker](https://github.com/pinguinjkeke/react-native-wheel-datepicker) ## Preview ![](https://i.ibb.co/4W7h12M/rn-wl-pk-1-1-13.png) ## Note - For Picker of iOS use [@react-native-picker/picker](https://github.com/react-native-picker/picker) - For DatePicker of iOS use [@react-native-community/datetimepicker](https://github.com/react-native-datetimepicker/datetimepicker) - For Picker and DatePicker of Android use WheelPicker of [AigeStudio](https://github.com/AigeStudio/WheelPicker) ## How to use React Native >= 0.60+ ``` npm install react-native-wheel-pick --save-dev --legacy-peer-deps npm install @react-native-picker/picker --save-dev --legacy-peer-deps npm install @react-native-community/datetimepicker --save-dev --legacy-peer-deps npx pod-install npx react-native start --reset-cache // clear cache npx react-native run-ios // re-build native-code npx react-native run-android // re-build native-code for gradle ``` React Native < 0.60 ``` npm install react-native-wheel-pick react-native link react-native-wheel-pick ``` ## Example code ```jsx import { Picker, DatePicker } from 'react-native-wheel-pick'; // use Picker { console.log(value) }} /> // use DatePicker { console.log(date) }} /> // for TypeScript onValueChange={(value: string) => { console.log(value) }} onDateChange={(date: Date) => { console.log(date) }} ``` ## More Example ```jsx // Set Text Color // DatePicker set default select date { console.log(date) }} /> // DatePicker set min/max Date { console.log(date) }} /> ``` ```jsx // pickerData also support array of object. (Optional Way) // Normal Way { console.log(value) }} /> // Optional Way // `label` only use for show Text to UI. // You cannot get `label` from onValueChange { console.log(value) }} // '5765387680' /> ``` ```jsx // Android Only. // These is special props for Android. (iOS and Web not work) // You can also use these props for DatePicker, too. // Android Only. // Test on Web (Platform.OS === 'Web') // DatePicker still not supported on Web. ``` ## How to change Font Family for Android 1. Goto `android/app/src/main/res/values/styles.xml` 2. Add this code `fonts/[FONT_NAME].ttf` Thanks to [@RMabroukS](https://github.com/TronNatthakorn/react-native-wheel-pick/issues/58) ## FYI I rarely check this lib. (6 Months - 3 Years). Up on my life's time. If you want to pay me coffee for quickly check & merge your request. You can sponsor me [![](https://img.shields.io/static/v1?label=Sponsor&message=%E2%9D%A4&logo=GitHub&color=%23fe8e86)](https://github.com/sponsors/TronNatthakorn) OR you can fork this project instead. ## Release Note ### 1.2.8 (Feb 14 2026) [Android] - Add support for decimal number on Native Android. Thanks to [@ArnaudDerosin](https://github.com/TronNatthakorn/react-native-wheel-pick/pull/69) ### 1.2.6 (Jul 5 2025) [Android] - Add support for `isCyclic` property on Android. (Infinitely Scrolling) Thanks to [@cip123](https://github.com/TronNatthakorn/react-native-wheel-pick/pull/67) ### 1.2.5 (Jun 14 2025) [Android] - Fix Android DatePicker time mode default selection issue and correct hour range. Thanks to [@harryxu](https://github.com/TronNatthakorn/react-native-wheel-pick/pull/66) ### 1.2.4 (Feb 17 2025) [Web] - Test on `Platform.OS === 'web'` - Only `` can use on Web. `` still not supported on Web. ### 1.2.3 (Feb 15 2024) - Fix state is not updating after onValueChange in Picker Component. Thanks to [@spasma ](https://github.com/TronNatthakorn/react-native-wheel-pick/issues/52) - Test on React Native Version 0.77 [Android] - Support [UIManager New Architecture of React Native](https://github.com/reactwg/react-native-new-architecture/discussions/201) - Use Handler for fix 23 index problem. Thanks to [@mykhailoperemitko](https://github.com/TronNatthakorn/react-native-wheel-pick/issues/44) [@A-ANing](https://github.com/A-ANing) ### 1.2.2 (June 7 2023) [iOS] - Now iOS can use `textColor`, too. [Add missing color option for iOS](https://github.com/TronNatthakorn/react-native-wheel-pick/pull/38) [@aurotones](https://github.com/aurotones) ### 1.2.1 (June 4 2023) - Fix typescript warning [Android] - Update compileSDK to version 33. ### 1.2.0 (July 3 2022) - Remove `deprecated-react-native-prop-types` - Support for peer dependencies React 18 by `--legacy-peer-deps` ### 1.1.7 (June 21 2022) [Android] - compileSdk -> compileSdkVersion ### 1.1.6 (June 20 2022) - Add more step for How to use ### 1.1.5 (June 20 2022) - Change License from MIT to Apache-2.0 - Add NOTICE file for credit original author. - Fix peerDependency do not break other version. [Android] - Fix WheelCurvedPicker not found for first run. - DatePicker support order prop. ### 1.1.4 (June 19 2022) - Fix Readme wrong type. ### 1.1.3 (June 19 2022) - Restructure code of Picker iOS and Android. - pickerData support array of object. [Android] - Update sdk support for SDK Version 30 (Google Play need sdk version 30+) - Now android support for style of selectLine / selectBackground. Special thanks to [@kaisv7n](https://github.com/kaisv7n) for his pull request, [Update WheelPicker version, exposed more methods and fixed crash on android](https://github.com/TronNatthakorn/react-native-wheel-pick/pull/12) I changed prop name for more understandable. - DatePicker of Android also support width. - Deprecated some android prop that make library faster. (Atmospheric / Curved / visibleItemCount / itemSpace) If you want it back pull request are welcome. - Change some prop name for make code more understandable. - If update from version <= 1.1.2. You will get warning about Deprecated prop if you still use, I write some logic for make app not crash. (Please fix warning if possible.) [IOS] - Do not use PickerIOS and DatePickerIOS of 'react-native' anymore. ## Preview for version <= 1.12 ![](https://preview.ibb.co/iUjDZo/screen1.png) ## Example code for version <= 1.12 ```jsx import { Platform } from 'react-native'; import { Picker, DatePicker } from 'react-native-wheel-pick'; const isIos = Platform.OS === 'ios' // use Picker { }} itemSpace={30} // this only support in android /> // use DatePicker { }} /> ``` ## Note for version <= 1.12 - For iOS use default PickerIOS / DatePickerIOS of React Native. - For Android use WheelPicker of [WheelPicker](https://github.com/AigeStudio/WheelPicker) - Line color is white in android. (Support Line style in future. Pull request welcome) - Line color is grey in IOS but it has bug line not show in Picker (iOS 11.4 not sure other version). ## More Example for version <= 1.12 ```jsx // DatePicker set default choose date { }} /> // DatePicker set min/max Date { }} /> ``` ## Release Note for version <= 1.12 ### 1.1.2 (April 13 2022) - Edit broken url. ### 1.1.1 (November 20 2021) - Edit broken url. ### 1.1.0 (January 14 2020) - Use react-native.config.js instead of rnpm section. [@darkbluesun](https://github.com/darkbluesun) [Android] - Add safeExtGet to get sdk version from root project.[@darkbluesun](https://github.com/darkbluesun) ### 1.0.9 (June 27 2018) [IOS] - Fix bug props date of DatePicker is not work right. ### 1.0.8 (June 27 2018) - Support props for date picker (date / minimumDate / maximumDate) [IOS] - Fix bug cannot read property 'getTime' of null ### 1.0.7 (June 25 2018) [Android] - Fix bug android value wrong from array ### 1.0.5 (June 24 2018) - Fix Lifecycle for support React 16 (Remove componentWillMount / componentWillReceiveProps) [Android] - Fix bug onValueChange occur first time without change ### 1.0.4 (June 24 2018) [Android] - Support compileSDKVersion 26 ## License Copyright 2022 tron.natthakorn@engineer.com Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: android/build.gradle ================================================ buildscript { repositories { maven { url "https://jitpack.io" } } } apply plugin: 'com.android.library' def isNewArchitectureEnabled() { return project.hasProperty("newArchEnabled") && project.newArchEnabled == "true" } if (isNewArchitectureEnabled()) { apply plugin: 'com.facebook.react' } android { compileSdkVersion 33 namespace 'com.tron' defaultConfig { buildConfigField("boolean", "IS_NEW_ARCHITECTURE_ENABLED", isNewArchitectureEnabled().toString()) } buildFeatures { buildConfig true } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation "com.github.AigeStudio:WheelPicker:5913fa15fc" implementation 'com.facebook.react:react-native:+' } ================================================ FILE: android/src/main/AndroidManifest.xml ================================================ ================================================ FILE: android/src/main/java/com/tron/ReactNativeWheelPickerPackage.java ================================================ package com.tron; import com.facebook.react.ReactPackage; import com.facebook.react.bridge.JavaScriptModule; import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.uimanager.ViewManager; import java.util.Arrays; import java.util.Collections; import java.util.List; public class ReactNativeWheelPickerPackage implements ReactPackage { @Override public List createNativeModules(ReactApplicationContext reactContext) { return Collections.emptyList(); } public List> createJSModules() { return Collections.emptyList(); } @Override public List createViewManagers(ReactApplicationContext reactContext) { return Arrays.asList( new ReactWheelCurvedPickerManager() ); } } ================================================ FILE: android/src/main/java/com/tron/ReactWheelCurvedPicker.java ================================================ package com.tron; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.LinearGradient; import android.graphics.Paint; import android.graphics.Shader; import android.os.SystemClock; import android.util.AttributeSet; // import android.util.Log; import com.aigestudio.wheelpicker.WheelPicker; import com.aigestudio.wheelpicker.WheelPicker.OnWheelChangeListener; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.ReactContext; import com.facebook.react.bridge.WritableMap; import com.facebook.react.uimanager.UIManagerModule; import com.facebook.react.uimanager.events.Event; import com.facebook.react.uimanager.events.EventDispatcher; import com.facebook.react.uimanager.events.RCTEventEmitter; import com.facebook.react.uimanager.UIManagerHelper; // UIManagerType; import com.facebook.react.uimanager.common.UIManagerType; import java.util.Date; import java.util.List; /** * Credit Author: Sam Yu */ public class ReactWheelCurvedPicker extends WheelPicker { private final EventDispatcher mEventDispatcher; private List mValueData; //private int mState; public ReactWheelCurvedPicker(ReactContext reactContext) { super(reactContext); if(BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) { mEventDispatcher = (UIManagerHelper.getUIManager(reactContext, 1 /** UIManagerType */)).getEventDispatcher(); } else { mEventDispatcher = reactContext.getNativeModule(UIManagerModule.class).getEventDispatcher(); } setOnWheelChangeListener(new OnWheelChangeListener() { @Override public void onWheelScrolled(int offset) { } @Override public void onWheelSelected(int position) { // Log.d("onWheelSelected", "Wheel Selected"); if (mValueData != null && position < mValueData.size()) { mEventDispatcher.dispatchEvent( new ItemSelectedEvent(getId(), mValueData.get(position))); } } @Override public void onWheelScrollStateChanged(int state) { //mState = state; } }); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); } public void setValueData(List data) { mValueData = data; } public void getState() { //public int getState() { //return state; } } class ItemSelectedEvent extends Event { public static final String EVENT_NAME = "wheelCurvedPickerPageSelected"; private final Object mValue; protected ItemSelectedEvent(int viewTag, Object value) { super(viewTag); mValue = value; } @Override public String getEventName() { return EVENT_NAME; } @Override public void dispatch(RCTEventEmitter rctEventEmitter) { rctEventEmitter.receiveEvent(getViewTag(), getEventName(), serializeEventData()); } private WritableMap serializeEventData() { WritableMap eventData = Arguments.createMap(); Class mValueClass = mValue.getClass(); if (mValueClass == Integer.class) { eventData.putInt("data", (Integer) mValue); } else if (mValueClass == Double.class) { eventData.putDouble("data", (Double) mValue); } else if (mValueClass == String.class) { eventData.putString("data", mValue.toString()); } return eventData; } } ================================================ FILE: android/src/main/java/com/tron/ReactWheelCurvedPickerManager.java ================================================ package com.tron; import android.graphics.Color; import android.os.Handler; import com.aigestudio.wheelpicker.WheelPicker; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.bridge.ReadableType; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.common.MapBuilder; import com.facebook.react.uimanager.PixelUtil; import com.facebook.react.uimanager.SimpleViewManager; import com.facebook.react.uimanager.ThemedReactContext; import com.facebook.react.uimanager.annotations.ReactProp; // import android.util.Log; import java.util.ArrayList; import java.util.Map; /** * Credit Author: Sam Yu */ public class ReactWheelCurvedPickerManager extends SimpleViewManager { private static final String REACT_CLASS = "WheelCurvedPicker"; private static final int DEFAULT_TEXT_SIZE = 24 * 2; private static final int DEFAULT_ITEM_SPACE = 16 * 2; @Override public Map getExportedCustomDirectEventTypeConstants() { return MapBuilder.of( ItemSelectedEvent.EVENT_NAME, MapBuilder.of("registrationName", "onValueChange") ); } @Override protected ReactWheelCurvedPicker createViewInstance(ThemedReactContext reactContext) { ReactWheelCurvedPicker picker = new ReactWheelCurvedPicker(reactContext); picker.setItemTextColor(Color.BLACK); picker.setItemTextSize(DEFAULT_TEXT_SIZE); picker.setSelectedItemTextColor(Color.WHITE); picker.setItemSpace(DEFAULT_ITEM_SPACE); picker.setIndicator(true); picker.setIndicatorSize(4); picker.setIndicatorColor(Color.parseColor("#26808080")); picker.setCurtain(true); picker.setCurtainColor(Color.parseColor("#1A808080")); picker.setAtmospheric(true); picker.setCurved(true); picker.setVisibleItemCount(7); picker.setItemAlign(0); // Trick Code - wake setSelectItemPosition picker.setSelectedItemPosition(1); // Cannot 0 instead of 1, I Don Know why but need this line for make ReactProp selectIndex Work return picker; } @ReactProp(name="data") public void setData(ReactWheelCurvedPicker picker, ReadableArray items) { if (picker != null) { ArrayList valueData = new ArrayList<>(); ArrayList labelData = new ArrayList<>(); for (int i = 0; i < items.size(); i ++) { ReadableMap itemMap = items.getMap(i); if (itemMap.getType("value") == ReadableType.String) { valueData.add(itemMap.getString("value")); } else if (itemMap.getType("value") == ReadableType.Number) { // valueData.add(itemMap.getInt("value")); // Store as Double to preserve decimal precision valueData.add(itemMap.getDouble("value")); } labelData.add(itemMap.getString("label")); } picker.setValueData(valueData); picker.setData(labelData); } } @ReactProp(name="selectedIndex") public void setSelectedIndex(ReactWheelCurvedPicker picker, int index) { //if (picker != null && picker.getState() == WheelPicker.SCROLL_STATE_IDLE) { // Log.d("Index from React", index + ""); if (picker != null) { // picker.setSelectedItemPosition(index); // picker.invalidate(); final Handler handler = new Handler(); handler.post(new Runnable() { @Override public void run() { picker.setSelectedItemPosition(index); picker.invalidate(); } }); } } // @ReactProp(name="atmospheric") // public void setAtmospheric(ReactWheelCurvedPicker picker, boolean hasAtmospheric) { // if (picker != null) { // picker.setAtmospheric(hasAtmospheric); // } // } // @ReactProp(name="curved") // public void setCurved(ReactWheelCurvedPicker picker, boolean hasCurved) { // if (picker != null) { // picker.setCurved(hasCurved); // } // } // @ReactProp(name="visibleItemCount") // public void setVisibleItemCount(ReactWheelCurvedPicker picker, int num) { // if (picker != null) { // picker.setVisibleItemCount(num); // } // } // // Didnot work on android 11 // @ReactProp(name="itemSpace") // public void setItemSpace(ReactWheelCurvedPicker picker, int space) { // if (picker != null) { // picker.setItemSpace((int) PixelUtil.toPixelFromDIP(space)); // } // } @ReactProp(name="textColor", customType = "Color") public void setTextColor(ReactWheelCurvedPicker picker, Integer color) { if (picker != null) { picker.setItemTextColor(color); } } @ReactProp(name="textSize") public void setTextSize(ReactWheelCurvedPicker picker, int size) { if (picker != null) { picker.setItemTextSize((int) PixelUtil.toPixelFromDIP(size)); } } @ReactProp(name="selectTextColor", customType = "Color") public void setSelectedTextColor(ReactWheelCurvedPicker picker, Integer color) { if (picker != null) { picker.setSelectedItemTextColor(color); } } //@ReactProp(name="curtain") @ReactProp(name="isShowSelectBackground") public void setCurtain(ReactWheelCurvedPicker picker, boolean hasCurtain) { if (picker != null) { picker.setCurtain(hasCurtain); } } //@ReactProp(name="curtainColor", customType = "Color") @ReactProp(name="selectBackgroundColor", customType = "Color") public void setCurtainColor(ReactWheelCurvedPicker picker, Integer color) { if (picker != null) { picker.setCurtainColor(color); } } // @ReactProp(name="indicator") @ReactProp(name="isShowSelectLine") public void setIndicator(ReactWheelCurvedPicker picker, boolean hasIndicator) { if (picker != null) { picker.setIndicator(hasIndicator); } } //@ReactProp(name="indicatorColor", customType = "Color") @ReactProp(name="selectLineColor", customType = "Color") public void setIndicatorColor(ReactWheelCurvedPicker picker, Integer color) { if (picker != null) { picker.setIndicatorColor(color); } } //@ReactProp(name="indicatorSize") @ReactProp(name="selectLineSize") public void setIndicatorSize(ReactWheelCurvedPicker picker, int size) { if (picker != null) { picker.setIndicatorSize(size); } } // @ReactProp(name="isCyclic") @ReactProp(name="isCyclic") public void setCyclic(ReactWheelCurvedPicker picker, boolean isCyclic) { if (picker != null) { picker.setCyclic(isCyclic); } } @Override public String getName() { return REACT_CLASS; } } ================================================ FILE: package.json ================================================ { "name": "react-native-wheel-pick", "version": "1.2.8", "description": "React native wheel picker iOS style with android.", "main": "src/index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url": "git+https://github.com/TronNatthakorn/react-native-wheel-pick.git" }, "keywords": [ "react-native", "react-native-wheel", "react-native-wheel-pick", "react-native-wheel-picker" ], "author": "Tron Natthakorn ", "license": "Apache-2.0", "bugs": { "url": "https://github.com/TronNatthakorn/react-native-wheel-pick/issues" }, "homepage": "https://github.com/TronNatthakorn/react-native-wheel-pick#readme", "dependencies": { "moment": "^2.19.1" }, "peerDependencies": { "moment": ">=2.0.0", "prop-types": "*", "@react-native-community/datetimepicker": ">=6.1.3", "@react-native-picker/picker": ">=2.4.1" } } ================================================ FILE: react-native.config.js ================================================ module.exports = { dependency: { platforms: { android: { packageInstance: "new ReactNativeWheelPickerPackage()" } } } }; ================================================ FILE: src/WheelCurvedPicker.android.js ================================================ import React, { PureComponent } from 'react'; import { requireNativeComponent, View } from 'react-native'; // import { ColorPropType, ViewPropTypes as RNViewPropTypes, } from 'deprecated-react-native-prop-types' import PropTypes from 'prop-types'; // const ViewPropTypes = RNViewPropTypes || View.propTypes; let firstTimeOnChange = true const stateFromProps = (props) => { let selectedIndex = 0; const items = props.children.map(({ props: { value, label } }, index) => { if (value === props.selectedValue) { selectedIndex = index; } return { value, label }; }); return { selectedIndex, items }; }; class WheelCurvedPicker extends PureComponent { static propTypes = { // ...ViewPropTypes, data: PropTypes.array, // textColor: ColorPropType, textSize: PropTypes.number, onValueChange: PropTypes.func.isRequired, selectedValue: PropTypes.any, // selectedIndex: PropTypes.number, }; static defaultProps = { textSize: 26, textColor: '#333', }; state = { selectedIndex: 0 } onValueChange = ({ nativeEvent: { data } }) => { this.props.onValueChange(data); if(firstTimeOnChange) { return firstTimeOnChange = false } } // componentDidMount() { // this.setState(stateFromProps(this.props)); // } static getDerivedStateFromProps(nextProps) { return stateFromProps(nextProps) } render() { const { children, ...otherProps } = this.props; return ( ); } } class Item extends PureComponent { static propTypes = { value: PropTypes.any.isRequired, label: PropTypes.string.isRequired, }; // These items don't get rendered directly. render = () => <>; } WheelCurvedPicker.Item = Item; const WheelCurvedPickerNative = requireNativeComponent('WheelCurvedPicker', WheelCurvedPicker); export default WheelCurvedPicker; ================================================ FILE: src/WheelCurvedPicker.ios.js ================================================ import React from 'react'; import { Picker } from '@react-native-picker/picker'; export default Picker; ================================================ FILE: src/WheelCurvedPicker.web.js ================================================ // Wait for future maintenance import React from 'react'; import { Picker } from '@react-native-picker/picker'; export default Picker; ================================================ FILE: src/date-picker.android.js ================================================ import React, { PureComponent } from 'react'; import { StyleSheet, View } from 'react-native'; // import { ColorPropType, ViewPropTypes as RNViewPropTypes } from 'deprecated-react-native-prop-types' import PropTypes from 'prop-types'; import moment from 'moment'; import Picker from './picker'; // const ViewPropTypes = RNViewPropTypes || View.propTypes; const firstTimeOnChange = { year: true, month: true, date: true, hour: true, minute: true, } const styles = StyleSheet.create({ picker: { flex: 1, }, row: { flexDirection: 'row', }, }); const stylesFromProps = props => ({ textColor: props.textColor, textSize: props.textSize, style: props.style, }); export default class DatePicker extends PureComponent { static propTypes = { labelUnit: PropTypes.shape({ year: PropTypes.string, month: PropTypes.array, date: PropTypes.string, }), order: PropTypes.string, date: PropTypes.instanceOf(Date), maximumDate: PropTypes.instanceOf(Date), minimumDate: PropTypes.instanceOf(Date), mode: PropTypes.oneOf(['date', 'time', 'datetime']), onDateChange: PropTypes.func.isRequired, // style: ViewPropTypes.style, // textColor: ColorPropType, textSize: PropTypes.number, }; static defaultProps = { labelUnit: { year: '', month: moment.months(), date: '' }, order: 'M-D-Y', mode: 'date', maximumDate: moment().add(10, 'years').toDate(), minimumDate: moment().add(-10, 'years').toDate(), date: new Date(), style: null, textColor: '#333', textSize: 26, }; constructor(props) { super(props); const { date, minimumDate, maximumDate, labelUnit } = props; this.state = { date, monthRange: [], yearRange: [] }; this.newValue = {}; this.parseDate(date); const mdate = moment(date); const dayNum = mdate.daysInMonth(); this.state.dayRange = this.genDateRange(dayNum); const minYear = minimumDate.getFullYear(); const maxYear = maximumDate.getFullYear(); for (let i = 1; i <= 12; i += 1) { this.state.monthRange.push({ value: i, label: `${labelUnit.month[i - 1]}` }); } this.state.yearRange.push({ value: minYear, label: `${minYear}${labelUnit.year}` }); for (let i = minYear + 1; i <= maxYear; i += 1) { this.state.yearRange.push({ value: i, label: `${i}${labelUnit.year}` }); } } static getDerivedStateFromProps(nextProps, prevState) { if (prevState.date !== nextProps.date) { if(typeof this === 'object' && typeof this.parseDate === 'function'){ this.parseDate(nextProps.date); } return { date: nextProps.date } } else return null; } parseDate = (date) => { const mdate = moment(date); ['year', 'month', 'date', 'hour', 'minute'].forEach((s) => { this.newValue[s] = mdate.get(s); }); } onYearChange = (year) => { const oldYear = this.newValue.year; this.newValue.year = year; this.checkDate(oldYear, this.newValue.month); if(firstTimeOnChange.year) { firstTimeOnChange.year = false } this.props.onDateChange(this.getValue()); }; onMonthChange = (month) => { const oldMonth = this.newValue.month; this.newValue.month = month - 1; this.checkDate(this.newValue.year, oldMonth); if(firstTimeOnChange.month) { firstTimeOnChange.month = false } this.props.onDateChange(this.getValue()); }; onDateChange = (date) => { this.newValue.date = date; this.checkDate(this.newValue.year, this.newValue.month); if(firstTimeOnChange.date) { firstTimeOnChange.date = false } this.props.onDateChange(this.getValue()); }; onHourChange = (hour) => { this.newValue.hour = hour; if(firstTimeOnChange.hour) { firstTimeOnChange.hour = false } this.props.onDateChange(this.getValue()); }; onMinuteChange = (minute) => { this.newValue.minute = minute; if(firstTimeOnChange.minute) { firstTimeOnChange.minute = false } this.props.onDateChange(this.getValue()); }; genDateRange(dayNum) { const days = []; for (let i = 1; i <= dayNum; i += 1) { days.push({ value: i, label: `${i}${this.props.labelUnit.date}` }); } return days; } render() { const width_wrapper = this.props.style.width || '100%'; return ( {['date', 'datetime'].includes(this.props.mode) && this.datePicker} {['time', 'datetime'].includes(this.props.mode) && this.timePicker} ); } get datePicker() { const propsStyles = stylesFromProps(this.props); const { order } = this.props; if (!order.includes('D') && !order.includes('M') && !order.includes('Y')) { throw new Error(`WheelDatePicker: you are using order prop wrong, default value is 'D-M-Y'`); } return this.props.order.split('-').map((key) => { switch (key) { case 'D': return ( { this.dateComponent = date; }} selectedValue={this.state.date.getDate()} pickerData={this.state.dayRange} onValueChange={this.onDateChange} /> ); case 'M': return ( { this.monthComponent = month; }} selectedValue={this.state.date.getMonth() + 1} pickerData={this.state.monthRange} onValueChange={this.onMonthChange} /> ); case 'Y': return ( { this.yearComponent = year; }} selectedValue={this.state.date.getFullYear()} pickerData={this.state.yearRange} onValueChange={this.onYearChange} /> ); default: return null; } }) } get timePicker() { const propsStyles = stylesFromProps(this.props); const [hours, minutes] = [[], []]; for (let i = 0; i <= 23; i += 1) { // hours.push(i); hours.push({ value: i, label: `${i}` }) } for (let i = 0; i <= 59; i += 1) { // minutes.push(i); minutes.push({ value: i, label: `${i}` }) } return [ { this.hourComponent = hour; }} {...propsStyles} selectedValue={this.state.date.getHours()} pickerData={hours} onValueChange={this.onHourChange} /> , { this.minuteComponent = minute; }} {...propsStyles} selectedValue={this.state.date.getMinutes()} pickerData={minutes} onValueChange={this.onMinuteChange} /> , ]; } checkDate(oldYear, oldMonth) { const currentMonth = this.newValue.month; const currentYear = this.newValue.year; const currentDay = this.newValue.date; let dayRange = this.state.dayRange; let dayNum = dayRange.length; if (oldMonth !== currentMonth || oldYear !== currentYear) { dayNum = moment(`${currentYear}-${currentMonth + 1}`, 'YYYY-MM').daysInMonth(); } if (dayNum !== dayRange.length) { dayRange = this.genDateRange(dayNum); if (currentDay > dayNum) { this.newValue.date = dayNum; this.dateComponent.setState({ selectedValue: dayNum }); } this.setState({ dayRange }); } const unit = this.props.mode === 'date' ? 'day' : undefined; const current = Object.assign({}, this.newValue, { date: this.newValue.date }); let currentTime = moment(current); const min = moment(this.props.minimumDate); const max = moment(this.props.maximumDate); let isCurrentTimeChanged = false; if (currentTime.isBefore(min, unit)) { [currentTime, isCurrentTimeChanged] = [min, true]; } else if (currentTime.isAfter(max, unit)) { [currentTime, isCurrentTimeChanged] = [max, true]; } if (isCurrentTimeChanged) { if (this.monthComponent) { this.monthComponent.setState({ selectedValue: currentTime.get('month') + 1 }); } ['year', 'date', 'hour', 'minute'].forEach((segment) => { const ref = this[`${segment}Component`]; return ref && ref.setState({ selectedValue: currentTime.get(segment) }); }); } } getValue() { const { year, month, date, hour, minute } = this.newValue; const nextDate = new Date(Date.UTC(year, month, date, hour, minute)); if (nextDate < this.props.minimumDate) { return this.props.minimumDate; } return nextDate > this.props.maximumDate ? this.props.maximumDate : nextDate; } } ================================================ FILE: src/date-picker.ios.js ================================================ import React, { PureComponent } from 'react'; // import { DatePickerIOS } from 'react-native'; import DateTimePicker from '@react-native-community/datetimepicker'; import PropTypes from 'prop-types'; export default class DatePicker extends PureComponent { static propTypes = { date: PropTypes.instanceOf(Date), maximumDate: PropTypes.instanceOf(Date), minimumDate: PropTypes.instanceOf(Date), mode: PropTypes.oneOf(['date', 'time', 'datetime']), onDateChange: PropTypes.func.isRequired, }; static defaultProps = { mode: 'date', date: new Date(), }; state = { date: new Date(), }; // @react-native-community/datetimepicker //2022 use value instead of date //2022 use onChange instead of onDateChange (and first param not date anymore) render() { return ( this.onDateChange(date)} display='spinner' value={this.state.date} /> ); } componentDidMount() { this.setState({ date: this.props.date }) } componentDidUpdate(prevProps) { if (this.props.date !== prevProps.date) { this.setState({ date: this.props.date }) } } onDateChange = (date) => { this.setState({ date }); this.props.onDateChange(date); } } ================================================ FILE: src/date-picker.web.js ================================================ import React, { PureComponent } from 'react'; // import { DatePickerIOS } from 'react-native'; import DateTimePicker from '@react-native-community/datetimepicker'; import PropTypes from 'prop-types'; export default class DatePicker extends PureComponent { static propTypes = { date: PropTypes.instanceOf(Date), maximumDate: PropTypes.instanceOf(Date), minimumDate: PropTypes.instanceOf(Date), mode: PropTypes.oneOf(['date', 'time', 'datetime']), onDateChange: PropTypes.func.isRequired, }; static defaultProps = { mode: 'date', date: new Date(), }; state = { date: new Date(), }; // @react-native-community/datetimepicker //2022 use value instead of date //2022 use onChange instead of onDateChange (and first param not date anymore) render() { return ( this.onDateChange(date)} display='spinner' value={this.state.date} /> ); } componentDidMount() { this.setState({ date: this.props.date }) } componentDidUpdate(prevProps) { if (this.props.date !== prevProps.date) { this.setState({ date: this.props.date }) } } onDateChange = (date) => { this.setState({ date }); this.props.onDateChange(date); } } ================================================ FILE: src/index.d.ts ================================================ 'use strict'; import { Platform } from 'react-native'; import Picker from './picker'; import DatePicker from './date-picker'; let DatePickerComponent = DatePicker; export const registerCustomDatePickerIOS = (CustomDatePickerIOS) => { if (Platform.OS === 'ios') { DatePickerComponent = CustomDatePickerIOS; } return DatePickerComponent; }; export const Picker; export const DatePicker; ================================================ FILE: src/index.js ================================================ 'use strict'; import { Platform } from 'react-native'; import Picker from './picker'; import DatePicker from './date-picker'; let DatePickerComponent = DatePicker; const registerCustomDatePickerIOS = (CustomDatePickerIOS) => { if (Platform.OS === 'ios') { DatePickerComponent = CustomDatePickerIOS; } return DatePickerComponent; }; module.exports = { Picker, DatePicker: DatePickerComponent, registerCustomDatePickerIOS }; ================================================ FILE: src/picker.js ================================================ import React, { Component } from 'react'; import { StyleSheet, View, Text, Platform } from 'react-native'; // import { ColorPropType, ViewPropTypes as RNViewPropTypes, } from 'deprecated-react-native-prop-types' import PropTypes from 'prop-types'; import WheelCurvedPicker from './WheelCurvedPicker'; // const ViewPropTypes = RNViewPropTypes || View.propTypes; const PickerItem = WheelCurvedPicker.Item; const styles = StyleSheet.create({ picker: { backgroundColor: '#d3d3d3', height: 220, }, }); export default class Picker extends Component { static propTypes = { // textColor: ColorPropType, textSize: PropTypes.number, // itemStyle: ViewPropTypes.style, onValueChange: PropTypes.func.isRequired, pickerData: PropTypes.array.isRequired, // style: ViewPropTypes.style, selectedValue: PropTypes.any, }; static defaultProps = { textColor: '#333', textSize: 26, itemStyle: null, // onValueChange: () => {}, // Require // pickerData: [''], // Require style: {}, selectedValue: '', }; state = { selectedValue: this.props.selectedValue, }; handleChange = (selectedValue) => { this.setState({ selectedValue }); this.props.onValueChange(selectedValue); }; componentDidUpdate(prevProps) { if (prevProps.selectedValue !== this.props.selectedValue) { this.setState({ selectedValue: this.props.selectedValue }); } } validateDeprecateProps = (oldProp = 'curtain', newProp = '') => { if(this.props){ if(typeof this.props[oldProp] !== 'undefined'){ this.props[oldProp] = undefined; if(newProp === ''){ console.warn(`react-native-wheel-pick : "${oldProp}" Prop was deprecated. Please remove it for improve native performance.`) } else { console.warn(`react-native-wheel-pick : "${oldProp}" Prop was deprecated. Please use "${newProp}" instead.`) } } } } render() { const { pickerData, style, ...props } = this.props; if(Platform.OS === 'android'){ //checkDeprecatedProp this.validateDeprecateProps('atmospheric'); this.validateDeprecateProps('curved'); this.validateDeprecateProps('visibleItemCount'); this.validateDeprecateProps('itemSpace'); this.validateDeprecateProps('curtain', 'isShowSelectBackground'); this.validateDeprecateProps('curtainColor', 'selectBackgroundColor'); this.validateDeprecateProps('indicator', 'isShowSelectLine'); this.validateDeprecateProps('indicatorColor', 'selectLineColor'); this.validateDeprecateProps('indicatorSize', 'selectLineSize'); } const propsForWeb = { ...props } if(Platform.OS === 'web'){ propsForWeb.textcolor = propsForWeb.textColor propsForWeb.textsize = propsForWeb.textSize propsForWeb.selecttextcolor = propsForWeb.selectTextColor propsForWeb.isshowselectbackground = propsForWeb.isShowSelectBackground.toString() propsForWeb.selectbackgroundcolor = propsForWeb.selectBackgroundColor propsForWeb.isshowselectline = propsForWeb.isShowSelectLine.toString() propsForWeb.selectlinecolor = propsForWeb.selectLineColor propsForWeb.selectlinesize = propsForWeb.selectLineSize delete propsForWeb.textColor delete propsForWeb.textSize delete propsForWeb.selectTextColor delete propsForWeb.isShowSelectBackground delete propsForWeb.selectBackgroundColor delete propsForWeb.isShowSelectLine delete propsForWeb.selectLineColor delete propsForWeb.selectLineSize } return ( {pickerData.map((data, index) => ( ))} ); } getValue() { return this.state.selectedValue; } }