How can I use react native datetime picker - react-native

As I want to use datepicker I'm getting this error
null is not an object (evaluating '_reactNative.NativeModules.RNDateTimePickerManager.getDefaultDisplayValue')
Source codes
import React, {useState} from 'react';
import DateTimePicker from '#react-native-community/datetimepicker';
const ExpenseStepThree = () => {
const [date, setDate] = useState(new Date());
const onChange = (event, selectedDate) => {
const currentDate = selectedDate || date;
setDate(currentDate);
};
return <DateTimePicker value={date} onChange={onChange} />;
};
export default ExpenseStepThree;
Measure to fix issue I did
pod-install
npm install #react-native-community/datetimepicker --save
Device specification
Xcode 12.5
"react": "17.0.2",
"#react-native-community/datetimepicker": "^3.5.2",
"react-native": "0.66.1",

Try react-native-modal-datetime-picker package instead.

Related

undefined is not an object _react.PropTypes.array

I am using React Native (Expo CLI). Since i reinstalled npm i have this error when i try to run npm start I found some similar erros related to react-native-snap-carousel (i am using it).
TypeError: undefined is not an object (evaluating '_react.PropTypes.array')
at node_modules\expo\build\environment\react-native-logs.fx.js:27:4 in error
at node_modules\react-native\Libraries\Core\ExceptionsManager.js:95:4 in reportException
at node_modules\react-native\Libraries\Core\ExceptionsManager.js:141:19 in handleException
at node_modules\react-native\Libraries\Core\setUpErrorHandling.js:24:6 in handleError
at node_modules\#react-native\polyfills\error-guard.js:49:36 in ErrorUtils.reportFatalError
at node_modules\metro-runtime\src\polyfills\require.js:203:6 in guardedLoadModule
at http://192.168.1.6:19000/node_modules%5Cexpo%5CAppEntry.bundle?platform=android&dev=true&hot=false&strict=false&minify=false:202384:3 in global code
So, inside it's main file is imported {PropTypes} from "react"; and changed to import PropTypes from "prop-types"; (previously installed). Also changed propTypes.items: PopTypes.array.isRequired to propTypes.items:PropTypes.array, same to slideStyle (because I started getting new errors related to items and slideStyle are required) but now i am receiving new errors like this.
All errors are related to react-native-snap-carousel
Here is my package.json
Here is how i use react-native-snap-carousel
import React, { useState, useEffect } from "react";
import {
View,
StyleSheet,
Image,
Dimensions,
TouchableWithoutFeedback,
} from "react-native";
import { getBannersApi } from "../../Api/HomeBanner";
import Carousel, { Pagination } from "react-native-snap-carousel";
import { size } from "lodash";
import { useNavigation } from "#react-navigation/native";
import { SERVER_RESOURCERS } from "../../Utils/Constans";
const width = Dimensions.get("window").width;
const height = 160;
export default function Banner() {
const [banners, setBanners] = useState(null);
const [banneActive, setBanneActive] = useState(0);
const navigation = useNavigation();
useEffect(() => {
(async () => {
const response = await getBannersApi();
setBanners(response.data);
})();
}, []);
const goToProduct = (id) => {
navigation.push("product", { idProduct: id });
};
if (!banners) return null;
const renderItem = ({ item }) => {
return (
<TouchableWithoutFeedback
onPress={() => goToProduct(item.attributes.product.data.id)}
>
<Image
style={styles.carousel}
source={{
uri: `${SERVER_RESOURCERS}${item.attributes.banner.data[0].attributes.formats.small.url}`,
}}
/>
</TouchableWithoutFeedback>
);
};
return (
<View style={styles.container}>
<Carousel
layout="default"
data={banners}
sliderWidth={width}
itemWidth={width}
renderItem={renderItem}
loop={true}
onSnapToItem={(i) => setBanneActive(i)}
autoplay={true}
autoplayInterval={5000}
autoplayDelay={2000}
/>
<Pagination
dotsLength={size(banners)}
activeDotIndex={banneActive}
inactiveDotOpacity={0.6}
inactiveDotScale={0.6}
containerStyle={styles.dotsContainer}
dotStyle={styles.dot}
dotColor={styles.dot.backgroundColor}
inactiveDotColor={styles.dot.backgroundColor}
/>
</View>
);
}
I noticed react-native-snap-carousel is not supported anymore so I migrated to react-native-reanimated-carousel

Module not found: Can't resolve './picker' with React Native DateTimePicker

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';
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.
Try to back version to 6.0.2
Seems it is the actual issue for some people: https://github.com/react-native-datetimepicker/datetimepicker/issues/626
UPD:
I've tried to run your example and it works. My package.json:
"dependencies": {
"expo": "~45.0.0",
"expo-status-bar": "~1.3.0",
"react": "17.0.2",
"react-dom": "17.0.2",
"react-native": "0.68.2",
"react-native-web": "0.17.7",
"#react-native-community/datetimepicker": "6.1.2"
},
If it won't help, try to reinstall node_modules and clear cash: https://facebook.github.io/metro/docs/troubleshooting/

How to Make Shaka Player Compatible with react Native?

I am working on React-Native application. i want to implement shaka player in react-native.
any solution?
Have you tried using the shaka-player npm package? You can use it within your React component and instantiate as state.
import React, { useRef, useState, useEffect } from 'react';
import shaka from 'shaka-player';
const Component = () => {
const playerRef = useRef();
const [videoPlayer, setVideoPlayer] = useState();
useEffect(() => {
if (!videoPlayer) {
const newPlayer = new shaka.Player(playerRef.current);
setVideoPlayer(newPlayer);
// you can start using shaka-player APIs with videoPlayer
}
}, []);
return (
<video ref={playerRef} />
);
}

How to stop Fast refresh reset route to initialRoute automatically in React Native

How are you.
I am using React Native 0.62.2.
The problem is when code updated, it goes to initalRoute automatically, so I need to navigate to screen I was working to check updated.
How can I stop it so when updated code, fast refresh shows update on current screen?
"react": "16.11.0",
"react-native": "0.62.2",
"#react-navigation/bottom-tabs": "^5.2.7",
"#react-navigation/drawer": "^5.5.0",
"#react-navigation/material-bottom-tabs": "^5.1.9",
"#react-navigation/native": "^5.1.5",
"#react-navigation/stack": "^5.2.10",
Thanks
For those who are running into this problem with React Native Web.
I fixed this by configuring Linking with React Navigation.
const config = {
screens: {
Login: 'login',
Home: '',
About: 'about',
},
};
const linking = {
prefixes: ['https://example.com',],
config,
};
<NavigationContainer linking={linking}>
...
</NavigationContainer>
Once Linking was set up, fast refresh no longer reseted the navigation to the first route.
You can write a component that record the state of the navigation and stores it on asyncStorage. Maybe something like so:
import { InitialState, NavigationContainer } from "#react-navigation/native";
import React, { useCallback, useEffect, useState } from "react";
import { AsyncStorage } from "react-native";
const NAVIGATION_STATE_KEY = `NAVIGATION_STATE_KEY-${sdkVersion}`;
function NavigationHandler() {
const [isNavigationReady, setIsNavigationReady] = useState(!__DEV__);
const [initialState, setInitialState] = useState<InitialState | undefined>();
useEffect(() => {
const restoreState = async () => {
try {
const savedStateString = await AsyncStorage.getItem(
NAVIGATION_STATE_KEY
);
const state = savedStateString
? JSON.parse(savedStateString)
: undefined;
setInitialState(state);
} finally {
setIsNavigationReady(true);
}
};
if (!isNavigationReady) {
restoreState();
}
}, [isNavigationReady]);
const onStateChange = useCallback(
(state) =>
AsyncStorage.setItem(NAVIGATION_STATE_KEY, JSON.stringify(state)),
[]
);
if (!isNavigationReady) {
return <AppLoading />;
}
return (
<NavigationContainer {...{ onStateChange, initialState }}>
{children}
</NavigationContainer>
);
}
I'd check LoadAsset Typescript component from #wcandillon here
Maybe you can try this way.
I follow the State persistence document of React Navigation to write the code down below.
https://reactnavigation.org/docs/state-persistence/
import * as React from 'react';
import { Linking, Platform } from 'react-native';
import AsyncStorage from '#react-native-community/async-storage';
import { NavigationContainer } from '#react-navigation/native';
const PERSISTENCE_KEY = 'NAVIGATION_STATE';
export default function App() {
const [isReady, setIsReady] = React.useState(__DEV__ ? false : true);
const [initialState, setInitialState] = React.useState();
React.useEffect(() => {
const restoreState = async () => {
try {
const initialUrl = await Linking.getInitialURL();
if (Platform.OS !== 'web' && initialUrl == null) {
// Only restore state if there's no deep link and we're not on web
const savedStateString = await AsyncStorage.getItem(PERSISTENCE_KEY);
const state = savedStateString ? JSON.parse(savedStateString) : undefined;
if (state !== undefined) {
setInitialState(state);
}
}
} finally {
setIsReady(true);
}
};
if (!isReady) {
restoreState();
}
}, [isReady]);
if (!isReady) {
return <ActivityIndicator />;
}
return (
<NavigationContainer
initialState={initialState}
onStateChange={(state) =>
AsyncStorage.setItem(PERSISTENCE_KEY, JSON.stringify(state))
}
>
{/* ... */}
</NavigationContainer>
);
}

Invariant Violation: Element type is invalid: expected a string using connect of react-redux

Supposedly, I've got a small problem, but can't tackle it.
I've got a small React-Native app, one screen only.
Redux is used as a store. It's being built via Expo. While using connect of react-redux, I've got the following error:
Invariant Violation: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.
Check the render method of Home.
The app works if the component rendered by Home component isn't wrapped by connect().
Attach some code below.
App.js
import React from "react";
import { createStackNavigator, createAppContainer } from 'react-navigation';
import Home from './src/pages/Home';
import { Provider } from 'react-redux';
import configureStore from './src/stores/store';
const { store } = configureStore();
function App() {
return (
<Provider store={store}>
<AppContainer />
</Provider>
)
}
const MainNavigator = createStackNavigator({
Home: { screen: Home }
},
{
headerMode: 'none',
navigationOptions: {
headerVisible: false,
}
}
);
const AppContainer = createAppContainer(MainNavigator);
export default App;
Home.js
import React from "react";
import { StyleSheet, View, Text, Dimensions } from "react-native";
import SwitchEventTypes from "../components/SwitchEventTypes";
class Home extends React.Component {
constructor() {
super();
}
render() {
return (
<View>
<SwitchEventTypes />
</View>
)
}
}
SwitchEventTypes.js
import React, { Component } from "react";
import { connect } from 'react-redux';
import { StyleSheet, View, Text, Dimensions, TouchableOpacity } from "react-native";
import { updateEventType } from '../actions/actions';
const mapDispatchToProps = (dispatch) => {
return {
updateEventType: (newEventType) => {
dispatch(updateEventType(newEventType));
}
};
};
const mapStateToProps = (state) => {
return {
eventType: state.filter.eventType,
};
};
class SwitchEventTypes extends React.Component {
constructor() {
super();
this.state = {
isSwitchEventTypeOn: true
}
this.handleEventTypeChange = this.handleEventTypeChange.bind(this);
}
handleEventTypeChange(newEventType) {
this.props.updateEventType(newEventType);
}
render() {
return (
<View style={styles.switchTypesContainer}>
{this.props.eventType === 'active' ? <Text>123</Text> :
<Text>456</Text>
}
</View>
)
}
}
export default connect(mapStateToProps, mapDispatchToProps)(SwitchEventTypes);
store.js
import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from '../reducers';
const middleware = [thunk];
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const composedEnhancers = composeEnhancers(
applyMiddleware(...middleware),
)
export default () => {
const store = createStore(rootReducer, composedEnhancers);
return { store };
};
package.json
"dependencies": {
"expo": "^32.0.6",
"expo-react-native-shadow": "^1.0.3",
"expo-svg-uri": "^1.0.1",
"prop-types": "^15.7.2",
"react": "16.8.6",
"react-native": "https://github.com/expo/react-native/archive/sdk-32.0.1.tar.gz",
"react-native-calendars": "^1.32.0",
"react-native-svg": "^9.4.0",
"react-navigation": "^3.9.1",
"react-redux": "^7.0.1",
"redux": "^4.0.1",
"redux-thunk": "^2.3.0",
"react-native-switch": "^1.5.0"
},
"devDependencies": {
"babel-preset-expo": "^5.0.0",
"redux-devtools-extension": "^2.13.8",
"schedule": "^0.4.0"
},
What may be the matter? Please, help. Thanks.
Your mapDispatchToProps is returning an object. You also don't need the extra returns as fat arrow functions already have an implicit return. Will make your code a little more readable.
const mapDispatchToProps = dispatch => ({
updateEventType: (newEventType) => dispatch(updateEventType(newEventType));
});
const mapStateToProps = state => {
eventType: state.filter.eventType, // might be worth your time to investigate selectors down the road
};