Issue
I would like to have a date input field in a react-native form and I installed React Native DateTimePicker with the command: expo install @react-native-community/datetimepicker
To get started I used the following component almost exactly as described in the documentation:
import DateTimePicker from '@react-native-community/datetimepicker';
import React, { useState } from 'react';
import { Button, View, Text } from 'react-native';
export default function Picker () {
const [date, setDate] = useState(new Date(1598051730000));
const [mode, setMode] = useState('date');
const [show, setShow] = useState(false);
const onChange = (event, selectedDate) => {
const currentDate = selectedDate;
setShow(false);
setDate(currentDate);
};
const showMode = (currentMode) => {
setShow(true);
setMode(currentMode);
};
const showDatepicker = () => {
showMode('date');
};
const showTimepicker = () => {
showMode('time');
};
return (
<View>
<View>
<Button onPress={showDatepicker} title="Show date picker!" />
</View>
<View>
<Button onPress={showTimepicker} title="Show time picker!" />
</View>
<Text>selected: {date.toLocaleString()}</Text>
{show && (
<DateTimePicker
testID="dateTimePicker"
value={date}
mode={mode}
is24Hour={true}
onChange={onChange}
/>
)}
</View>
);
}
Then imported in another component.
However I get the following error:
./node_modules/@react-native-community/datetimepicker/src/DateTimePickerAndroid.js:23
Module not found: Can't resolve './picker'
21 | validateAndroidProps,
22 | } from './androidUtils';
> 23 | import pickers from './picker';
24 |
25 | function open(props: AndroidNativeProps) {
26 | const {
./node_modules/@react-native-community/datetimepicker/src/androidUtils.js:6
Module not found: Can't resolve './picker'
4 | */
5 | import {ANDROID_DISPLAY, ANDROID_MODE, MIN_MS} from './constants';
> 6 | import pickers from './picker';
7 | import type {AndroidNativeProps, DateTimePickerResult} from './types';
8 | import {sharedPropsValidation} from './utils';
9 | import invariant from 'invariant';
Solution
This error shows up when importing this package in the web version of react-native. Since the picker doesn't work on web anyway the easiest workaround is to not import it on web.
The way to do that is to create a separate file for native code. If you have a DateTimePicker.jsx
file then rename it to DateTimePicker.native.jsx
, then create a new file named DateTimePicker.jsx
with the content:
export default function Picker() {
return <Text>Picker does not work on web.</Text>
}
Now you can import DateTimePicker from "DateTimePicker"
and the android/ios version will import the picker, while on web you will get the noop version.
Answered By - Reite
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.