Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all 6214 articles
Browse latest View live

Need help fixing or suppressing this tslint error: TS2742

$
0
0

I have this file in a react native project:

import styled, { withTheme } from 'styled-components';import { BaseText } from '../BaseText';export interface BodyProps {  textAlign?: string;  fontSize?: string;}export const Body = withTheme(styled(BaseText)<BodyProps>`  text-align: ${props => (props.textAlign ? props.textAlign : 'center')};  font-size: ${props => (props.fontSize ? props.fontSize : '16px')};`);

I upgraded react native from 0.61.5 to 0.63.2 and started getting this lint error wherever withTheme is being used:

TS2742: The inferred type of 'Body' cannot be named without areference to 'react-native/node_modules/@types/react'. This is likelynot portable. A type annotation is necessary.

I tried several things, but the error remains the same:

  1. Following this post, I added import React from "react";
  2. Tried to disable tslint by adding /* tslint:disable */ above the Body declaration
  3. Tried to disable tslint by adding // tslint:disable-next-line above the Body declaration
  4. Played with dependency versions. Currently I have "@types/react": "^16.9.49".

How can I use TypeScript in this case?

$
0
0

enter image description here

I have a Node.js server on my root directory and in the Client directory is a React Native app (expo), both using the TypeScript template. The issue is that the server what every file in the src directory and if I exclude the Client directory in the configuration, the TypeScript form React Native will no longer be working. Is there a way to have two separate TypeScript configs running?The config from Client directory to watch the Client and the config from foot to watch only the src directory.

Typescript forwardRef error in react native

$
0
0

I have onboarding and slide components . I am passing ref as a prop to slide component from onboarding component with forwardRef . It works fine but typescript gives me an error

My components are like below

const Onboarding = () => {  const { width } = useOrientation();  const scrollX = new Animated.Value(0);  const scroll = useRef<Animated.ScrollView>(null);  const onScroll = (event: any) => {    Animated.event([{ nativeEvent: { contentOffset: { x: scrollX } } }]);  };  return (<Box flex={1}><Animated.ScrollView        ref={scroll}        scrollEventThrottle={16}        onScroll={onScroll}        horizontal>        {slides.map((data, index) => (<Slide key={index} data={data} ref={scroll} {...{ index, scrollX }} />        ))}</Animated.ScrollView></Box>  );};interface SlideProps {  data: {    label: string;    description: string;    src: string;  };  scrollX: Animated.Value<0>;  index: number;}export const Slide = forwardRef<Animated.ScrollView, SlideProps>(  ({ data, scrollX, index }: SlideProps, ref) => {    const { width, height } = Dimensions.get("window");    const aspect = height / width;    return (<Box flex={1} width={width} backgroundColor="mainBackground"><TouchableOpacity          onPress={() =>              //error here            ref?.current?.getNode().scrollTo({ x: width * (index + 1), y: 0 })          }><Text>heyy</Text></TouchableOpacity></Box>    );  });

Error is like this;Property 'current' does not exist on type '((instance: ScrollView | null) => void) | MutableRefObject<ScrollView | null>'.How can I fix this issue ? Thanks.

How to call one saga at the end of another redux-saga

$
0
0

I have two sagas, one gets the cities, the other is the weather forecast for these cities (according to ID specialists), how can I make it so that the second saga is processed at the end of the first?method in which a call my sagas:

async componentDidMount() {    this.props.navigation.setOptions(this.navigationOptions);    //sagas call        await this.props.fetchCities();        await this.fetchForecastsHandler(this.props.userCities);  } ...some code fetchForecastsHandler(cities: ICIty[]) {    const ids = cities.map((el) => el.id);    this.props.fetchForecasts(ids);  }``...some code   render(){...}

My index.ts saga

export function* mySaga() {    yield takeEvery(types.FETCH_USERS_CITIES, fetchUserCitiesWorker);    yield takeEvery(types.REMOVE_CITY, removeUserCitiesWorker);    yield takeEvery(types.SEARCH_CITY, searchUserCitiesWorker);    yield takeEvery(types.FETCH_FORECAST, fetchForecastWorker);    yield takeEvery(types.ADD_NOTIFICATION, addNotificationWorker);    yield takeEvery(types.EDIT_NOTIFICATION, editNotificationWorker);    yield takeEvery(types.DELETE_NOTIFICATION, deleteNotificationsWorker);    yield takeEvery(types.FETCH_NOTIFICATION, fetchNotificationsWorker);}**FeychCityWorker saga:** export function* fetchUserCitiesWorker(callback?:any) {    try {        yield put({ type: types.FETCH_USERS_CITIES_START });        //const user = yield call(Api.fetchUser, action.payload.userId);        yield delay(2000,true)        yield put({ type: types.FETCH_USERS_CITIES_SUCCESS, payload: userCities });        console.log("fetchUserCitiesWorker worked sucess")        //callback?callback():null    } catch (e) {        yield put({ type: types.FETCH_USERS_CITIES_ERROR, error: e.message });    }}**also storage settings just in case:**const sagaMiddleware = createSagaMiddleware()export const store = createStore(  reducer,  applyMiddleware(sagaMiddleware))export const action = (type:string) => store.dispatch({type})sagaMiddleware.run(mySaga)

Successfully uploaded image to Cloudinary from React Native does not return URL

$
0
0

I'm trying to upload image from React Native app to Cloudinary.The image appears on Dashboard, but I don't get secure_url.

Here is my code:

  async uploadImage(photo: ImagePickerResponse, id: string): Promise<string> {    return new Promise<string>(async (resolve, reject) => {      const uploadPreset = 'bbbbbb';      const cloudName = 'aaaaa';      const body = new FormData();      const uri: string =        Platform.OS === 'android' ? photo.uri : photo.uri.replace('file://', '');      const type = photo.type;      const name = `eMia${id}.jpeg`;      const file = {uri, type, name};      body.append('file', file);      body.append('upload_preset', uploadPreset);      body.append('cloud_name', cloudName);      const url = `https://api.cloudinary.com/v1_1/${cloudName}/image/upload`;      fetch(url, {method: 'POST', body})        .then((res) => {          // I don't have Body here so i don't have the image url :(          console.log(res);          res.json();        })        .then((json) => {          console.log(json);          const url = json.secure_url;          console.log(url);          resolve(url);        })        .catch((err) => {          reject(err);        });    });  }

Response:

enter image description here

React: Build Connections Among Component

$
0
0

I am a beginner of React JS. Messing around to achieve VanJS event listeners.

For layout, I decide to store things like a panel, a button as individual component.

Now, I have a component Movie and another component Button, how can I trigger state change of Movie by Button.onclick()?.

In other words, how to modify a component by the event happening on another component?

Before posting, I have read:

but tons of method followed by really confused me.

  • useState
  • componentWillMount: immediately before initial rendering
  • componentDidMount: immediately after initial rendering
  • componentWillReceiveProps: when component receives new props
  • shouldComponentUpdate: before rendering, after receiving new props or state
  • componentWillUpdate: before rendering, after receiving new props or state.
  • componentDidUpdate: after component's updates are flushed to DOM
  • componentWillUnmount: immediately before removing component from DOM

Following is a demo, which contains a Movie card and a Button, when the button is clicked, I want the background colour of the Movie card to change

React TypeScript Code Sandbox

the code:

import * as React from "react";import "./styles.css";import styled from 'styled-components';function CSSPropertiesToComponent(dict:React.CSSProperties){  let str = '';  for(const [key, value] of Object.entries(dict)){      let clo = '';      key.split('').forEach(lt=>{          if(lt.toUpperCase() === lt){              clo += '-'+ lt.toLowerCase();          }else{              clo += lt;          }      });      str += clo +':'+ value +';';  }  return str;}class Movie extends React.Component<any, any>{  public static style:React.CSSProperties|object = {      width: "300px",      height: "120px",      display: "flex",      justifyContent: "space-around",      alignItems: "center",      borderRadius: "20px",      filter: "drop-shadow(0px 1px 3px #6d6d6d)",      WebkitFilter: "drop-shadow(3px 3px 3px #6d6d6d)",      backgroundColor: '#'+Math.floor(Math.random()*16777215).toString(16),      fontSize: '2.5rem',      margin: '20px',      color: '#fff',  }  props:React.ComponentProps<any>;  state:React.ComponentState;  constructor(props:any) {      super(props);      this.props = props;      this.state = {style: Object.assign({}, Movie.style)}      this.changeColor = this.changeColor.bind(this);  }  changeColor():void{      this.setState({style: Object.assign({}, Movie.style, {backgroundColor: '#'+Math.floor(Math.random()*16777215).toString(16)})});  }  render():JSX.Element{      let StyledMovie = styled.div`          ${CSSPropertiesToComponent(Movie.style)}      `;      return (<><StyledMovie>{this.props.title}</StyledMovie></>      )  }}export default function App() {  let MV = new Movie({title: 'the Avengers'});    return (<>            {MV.render()}<button onClick={MV.changeColor}>Change Color</button></>    )}

However, when clicking on the change colour button, it doesn't work and shows a warning:

Warning: Can't call setState on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the Movie component.

if anyone offers some suggestion, I will be so glad.

How to call one saga at the end of another redux-saga like a async await in redux-thunk

$
0
0

I have two sagas, one gets the cities, the other is the weather forecast for these cities (according to ID specialists), how can I make it so that the second saga is processed at the end of the first?method in which a call my sagas:

async componentDidMount() {    this.props.navigation.setOptions(this.navigationOptions);    //sagas call        await this.props.fetchCities();        await this.fetchForecastsHandler(this.props.userCities);  } ...some code fetchForecastsHandler(cities: ICIty[]) {    const ids = cities.map((el) => el.id);    this.props.fetchForecasts(ids);  }``...some code   render(){...}

My index.ts saga

export function* mySaga() {    yield takeEvery(types.FETCH_USERS_CITIES, fetchUserCitiesWorker);    yield takeEvery(types.REMOVE_CITY, removeUserCitiesWorker);    yield takeEvery(types.SEARCH_CITY, searchUserCitiesWorker);    yield takeEvery(types.FETCH_FORECAST, fetchForecastWorker);    yield takeEvery(types.ADD_NOTIFICATION, addNotificationWorker);    yield takeEvery(types.EDIT_NOTIFICATION, editNotificationWorker);    yield takeEvery(types.DELETE_NOTIFICATION, deleteNotificationsWorker);    yield takeEvery(types.FETCH_NOTIFICATION, fetchNotificationsWorker);}**FeychCityWorker saga:** export function* fetchUserCitiesWorker(callback?:any) {    try {        yield put({ type: types.FETCH_USERS_CITIES_START });        //const user = yield call(Api.fetchUser, action.payload.userId);        yield delay(2000,true)        yield put({ type: types.FETCH_USERS_CITIES_SUCCESS, payload: userCities });        console.log("fetchUserCitiesWorker worked sucess")        //callback?callback():null    } catch (e) {        yield put({ type: types.FETCH_USERS_CITIES_ERROR, error: e.message });    }}**also storage settings just in case:**const sagaMiddleware = createSagaMiddleware()export const store = createStore(  reducer,  applyMiddleware(sagaMiddleware))export const action = (type:string) => store.dispatch({type})sagaMiddleware.run(mySaga)

How to bundle Typescript with React native

$
0
0

I'm trying to create a library for react-native, now I'm using typescript and react-native-webview but now stuck in bundle using webpack. Here is my webpack config

module.exports = {    mode: 'production',    entry: './src/index.ts',    externals: {'react-native': true,    },    module: {        rules: [            {                test: /\.(ts|tsx)?$/,                include: path.resolve(__dirname, 'src'),                use: [                    {                        loader: 'babel-loader',                    },                ]            },        ],    },    resolve: {        extensions: [ '.tsx', '.ts', '.js' ],    },    output: {        filename: 'index.js',        path: path.resolve(__dirname, 'dist'),        libraryTarget: 'umd',        library: '',    },};

.babelrc

{"presets": ["@babel/preset-env","module:metro-react-native-babel-preset"  ]}

And I get this error when running webpack build

ERROR in ./node_modules/react-native-webview/lib/WebView.js 7:36Module parse failed: Unexpected token (7:36)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| // implementation which is produced by Expo SDK 37.0.0.1 implementation, with| // similar interface than the native ones have.> var WebView = function () { return (<View style={{|     alignSelf: 'flex-start',|     borderColor: 'rgb(255, 0, 0)',

Where is my wrong? Please help me


getting type error for style transform properties when with react-native-reanimated

$
0
0

I'm using"react-native": "0.59.10""react-native-reanimated": "^1.3.0"with typescriptI'm getting type error for transform properties

const Example = () => {  const { translationX, gestureHandler } = horizontalPanGestureHandler()  return (<View style={styles.container}><PanGestureHandler {...gestureHandler}><Animated.View style={{ transform: [{ translateX: translationX }] }} /></PanGestureHandler></View>  )}

Here's the error I'm gettingType error

Formik React-Native - How to Show Yup Validation Errors on Each Field in an Array of Objects

$
0
0

So I'm trying to make a list of contacts, here's the code:

Yup Schema:

export const Schema = Yup.object().shape({/**other fields */contacts: Yup.array().required('Required field').of(    Yup.object().required('Required!').shape({        id: Yup.number(),        name: Yup.string().required('Required field!'),        phone: Yup.string().required('Required field!'),        email: Yup.string().email('Type a valid Email!').required('Required field!')    }))})

Formik Component:

const Form = () => {return (<View>  <Formik     validationSchema={Schema}    initialValues: {        /* other values */        contacts: [            {                id: 0,                name: '',                phone: '',                email: ''            }        ]    }>{({ handleChange, handleBlur, handleSubmit, setFieldValue, errors, touched, values }) => {    function addNewContact() {        setFieldValue('contacts', [            ...values.contacts,            { id: values.contacts[values.contacts.length - 1].id + 1, name: '', phone: '', email: '' }        ])    }    return (        /**A lot of inputs here*/        {values.contacts.map(({ id, email, name, phone }, index) => (<View key={id}><Text>Name *</Text><Input                    value={name}                    onChangeText={handleChange(`contacts[${index}].name`)}                    onBlur={handleBlur(`contacts[${index}].name`)}                />                {(errors.contacts ? errors.contacts[index].name : false)&& (touched.contacts ? touched.contacts[index].name : false)&& <Text>{`${errors.contacts[index].name}`}</Text>}                /**Repeat the above with phone and email */</View>        ))}    )}}</Formik></View>)}export default Form

My problem is when displaying the errors, I can't access them. In the way that is written above, intellisense says that name from errors.contacts[index].name does not exist on type string | FormikErrors<IContactProps>

I've tried to remove the ternary operator condition, but it tells me that contacts is possibly undefined.

When I console.log(errors.contacts), it shows the array I was supose to be able to access with errors.contacts[index].name.

Even with that intellisense error, my code runs and works with 1 contact. When I add 2 or more contacts,the app throws when I text on an Input: undefined is not an object (evaluating errors.contacts[index].nome)

How can I properly access these errors on an Array of objects? Thanks for your help!

Is there an automatic software architecture diagrams and dependency graphs visualizer for typescript? [closed]

$
0
0

I have a need to read(and fix) third party softwares, wich in most times are really messy and hard to understand the architecture logic aplied.Today I`m using dyatko/arkit, wich is already helping me a lot!But is there any other tools or solutions that can help me understand others people codes?

How do I pass a Type to a statelles component in TypeScript

$
0
0

Well, I would like to use one component to render differents types of data, since im using typescript, i need to pass the type of data my flatlist will be using, by now, i only have music and playlist. Is there a way to pass these types by father? Because i would like to reuse these component

User type

type playlistType = {    id: string    name: string    user: userType}

Playlist type

type playlistType = {    id: string    name: string    user: userType}

Music type

type musicType = {    id: string    name: string    artist: string    album: string    releaseyear: Date    genre: string    duration: string    user: userType}

The Component

const scrollableView: React.FC<scrollableViewProps> = (props /* There is nothing coming to props yet */) => {    return (<FlatList <Type of data that cames>            /* The settings for flatlist */        />    )}

The Father component that will call the list twice

const Dashboard: React.FC<DashboardScreenProps> = ({navigation}) => {    let {loggedUser} = useContext(UserContext)    let [fetchedData, setFetchedData] = useState<fetchedDataType>({        playlists: [],        musics: []    })    /* Some code here thats not important */    return (<View style={Style.container}><View><Text>Playlists</Text><ScrollableView /> //The component I would like to pass playlist type</View><View><Text>Musics</Text><ScrollableView /> //The same component I would like to pass music type</View></View>    )}

Set Up Custom Component Type That Using TextInput props and make it work when useRef to the component

$
0
0

I am creating a custom component, the script is written in TypeScript using React's Hooks

My component will be using some of my typescript type and mix it with TextInput type (so i can access TextInput props)

This is my custom component sample code

import { Animated, Platform, TextInput, TextInputProps, View } from 'react-native'type PropsType = TextInputProps & { //Or should I using TextInput instead of TextInputProps?    myCustomProp?: string}const CustomTextField = (props: PropsType) => {    useEffect(() => {        return () => {            if(props.onSubmitEditing != undefined) {                props.onSubmitEditing()            }        }    }, [])    return (<View            style = {{            }}        />    )}export default CustomTextField

Then I import it on my screen and display it like this

<CustomTextField    placeholder = 'Password'    ref = {passwordInput}    secureTextEntry/>

and this is my ref variable

const passwordInput = useRef<typeof CustomTextField>(null)

but the typescript give me error when ref to the component

enter image description here

React Native: Set React Navigation's Screens Headers

$
0
0

I want to have the tabs from BottomTabsNavigator and the header from StackNavigator in the case of jwt = true.

Do someone know how can I do it?

You can find my navigation jsx below.

If I didn't give sufficient details, please ask me.

Thank you.

<NavigationContainer>  {jwt ? (<Bottom.Navigator><Bottom.Screen        name="ToDoList"        component={Home}        options={{          title: "Not To Do List",          tabBarIcon: ({ color }: any) => (<Icon name="check" color={color} size={28} />          ),        }}      /><Bottom.Screen        name="NotToDoList"        component={NotToDo}        options={{          title: "To Do List",          tabBarIcon: ({ color }: any) => (<FIcon name="ban" color={color} size={28} />          ),        }}      /><Bottom.Screen        name="Profile"        component={Profile}        options={{          tabBarIcon: ({ color }: any) => (<FIcon name="user" color={color} size={28} />          ),        }}      /></Bottom.Navigator>  ) : (<Stack.Navigator><Stack.Screen        name="SignIn"        component={SignIn}        options={{ ...centerTitle("Sign In"), headerLeft }}      /><Stack.Screen        name="SignUp"        component={SignUp}        options={{ ...centerTitle("Sign Up"), headerLeft }}      /></Stack.Navigator>  )}</NavigationContainer>

mobx: class method call when changing data

$
0
0

Сan I use the Mobx library to call a class method when data changes?

For example MyObject writes container['item'] = 10 and as a result the myaction method is called.

class MyElement extends Component<any> {    // modifiable data    container: any = [];    // method called when data (container) is modified    myaction() {        console.log('container was modified');        console.log(this.container);    }    render() {<MyObject container = {this.container} />    }}decorate(MyElement, {    container: observable} as any)

Could not locate shadow view with tag #5469

$
0
0

In my react native app, I have a screen called the HomeScreen (though it's not the first screen that we see when we open the screen). When I visit this screen, I don't see any warning. From the HomeScreen, I visit another screen, followed by another etc. Then, when I return to my HomeScreen, I see the warning that:

Could not locate shadow view with tag #5469, this is probably caused by a temporary inconsistency between native views and shadow views.

My navigation scheme looks like this:

export type AppStackParamList = {  Home: undefined;  AddFriend: undefined;  AllFavouriteLocations: undefined;  EditFavouriteLocation: undefined;}const NavigationStack = createStackNavigator<AppStackParamList>();....return (<Suspense fallback="loading"><Provider store={store}><StyleProvider style={getTheme(material)}><ApolloProvider client={client}><SafeAreaProvider><NavigationContainer><NavigationStack.Navigator                  initialRouteName="Test"                  screenOptions={{                    gestureEnabled: false,                  }}><NavigationStack.Screen                    name="Test"                    component={TestScreen}                    options={{ headerShown: false }}                  /><NavigationStack.Screen                    name="Home"                    component={HomeScreen}                    options={{ headerShown: false }}                  /><NavigationStack.Screen                    name="AddFriend"                    component={AddFriendScreen}                    options={{                      headerShown: false,                    }}                  /></NavigationStack.Navigator></NavigationContainer></SafeAreaProvider></ApolloProvider></StyleProvider></Provider></Suspense>  );};

The HomeScreen looks somewhat like this:

return (<View style={styles.container}><View style={styles.mapContainer}><MapContainer /></View><HamburgerIcon /><HomeSwipeablePanel /><View style={styles.buttonContainer}><EnterDestinationButton          resetLocation={resetLocation}          navigation={navigation}          locations={locations}        /></View></View>  );};const styles = StyleSheet.create({  mapContainer: {    flex: 3,  },  container: {    flex: 1,  },  buttonContainer: {    position: 'absolute',    width: '100%',    height: moderateScale(SCREEN_HEIGHT * 0.1),    bottom: scale(5),    alignItems: 'center',  },});

What could be the possible reasons for this warning?

Tests fail to run with Jest and React Native

$
0
0

Using React Native with Jest and TypeScript, when trying to run the tests I get:

Test suite failed to run    [BABEL] unknown: Preset /* your preset */ requires a filename to be set when babel is called directly,    babel.transform(code, { filename: 'file.ts', presets: [/* your preset */] });    See https://babeljs.io/docs/en/options#filename for more information.

Any idea what can cause this?

This is my jest section on package.json:

"jest": {"preset": "react-native","roots": ["<rootDir>/__tests__"    ],"setupFiles": ["<rootDir>/scripts/jest/setup.js","<rootDir>/node_modules/appcenter/test/AppCenterMock.js","<rootDir>/node_modules/appcenter-analytics/test/AppCenterAnalyticsMock.js","<rootDir>/node_modules/appcenter-crashes/test/AppCenterCrashesMock.js","<rootDir>/node_modules/appcenter-push/test/AppCenterPushMock.js","<rootDir>/node_modules/react-native-localization.js","./config/jest/mock.fetch.js","./config/jest/react-native-localization.js"    ],"moduleFileExtensions": ["ts","tsx","js"    ],"transform": {"^.+\\.(js)$": "<rootDir>/node_modules/babel-jest","\\.(ts|tsx)$": "<rootDir>/node_modules/ts-jest/preprocessor.js"    },"collectCoverage": true,"coverageDirectory": "coverage","coverageReporters": ["text-summary","html"    ],"testPathIgnorePatterns": ["\\.snap$","<rootDir>/node_modules/","<rootDir>/lib/"    ],"collectCoverageFrom": ["**/*.{js,jsx}","artifacts/**/*.js","!artifacts/**/*.spec.js","!artifacts/**/*.index.js","!<rootDir>/node_modules/"    ]  },

and this is my babel.config.js file:

module.exports = {  presets: ['module:metro-react-native-babel-preset'  ],  plugins: ['babel-plugin-transform-typescript-metadata',    ['@babel/plugin-proposal-decorators', { legacy: true }]  ],};

Type for material from './native-base-theme';

$
0
0

I am using a custom native-base style theme. It was created using this method:

https://docs.nativebase.io/Customize.html#theaming-nb-headref

import material from './native-base-theme/variables/material';import getTheme from './native-base-theme/components';
return (<Suspense fallback="loading"><Provider store={store}><StyleProvider style={getTheme(material)}>

When I use material, I get such Type errors:

Argument of type '{ platformStyle: string; platform: "ios" | "android" | "windows" | "macos" | "web"; headerStyle: string; iconStyle: string; contentStyle: string; expandedIconStyle: string; accordionBorderColor: string; ... 151 more ...; Inset: { ...; }; }' is not assignable to parameter of type '{ platformStyle: any; platform: "ios" | "android" | "windows" | "macos" | "web"; accordionBorderColor: string; accordionContentPadding: number; accordionIconFontSize: number; contentStyle: string; ... 180 more ...; Inset: { ...; }; }'.Type '{ platformStyle: string; platform: "ios" | "android" | "windows" | "macos" | "web"; headerStyle: string; iconStyle: string; contentStyle: string; expandedIconStyle: string; accordionBorderColor: string; ... 151 more ...; Inset: { ...; }; }' is missing the following properties from type '{platformStyle: any; platform: "ios" | "android" | "windows" | "macos" | "web";

How can I get rid of this?

material.js inside the native-base-themes folder looks like this:

import color from 'color';import { Platform, Dimensions, PixelRatio } from 'react-native';import { PLATFORM } from './commonColor';const deviceHeight = Dimensions.get('window').height;const deviceWidth = Dimensions.get('window').width;const platform = Platform.OS;const platformStyle = PLATFORM.MATERIAL;const isIphoneX =  platform === PLATFORM.IOS &&  (deviceHeight === 812 ||    deviceWidth === 812 ||    deviceHeight === 896 ||    deviceWidth === 896);export default {  platformStyle,  platform,  // Android  androidRipple: true,  androidRippleColor: 'rgba(256, 256, 256, 0.3)',  androidRippleColorDark: 'rgba(0, 0, 0, 0.15)',  buttonUppercaseAndroidText: true,  // Button  buttonFontFamily: 'Roboto',  get buttonPrimaryBg() {    return this.brandPrimary;  },  get buttonTextSizeLarge() {    return this.fontSizeBase * 1.5;  },  // Header  toolbarBtnColor: '#fff',  toolbarDefaultBg: '#3F51B5',  toolbarHeight: 56,  toolbarSearchIconSize: 23,  toolbarInputColor: '#fff',  searchBarHeight: platform === PLATFORM.IOS ? 30 : 40,  searchBarInputHeight: platform === PLATFORM.IOS ? 40 : 50,  toolbarBtnTextColor: '#fff',  toolbarDefaultBorder: '#3F51B5',  iosStatusbar: 'light-content',  get statusBarColor() {    return color(this.toolbarDefaultBg)      .darken(0.2)      .hex();  },  get darkenHeader() {    return color(this.tabBgColor)      .darken(0.03)      .hex();  },  // Text  textColor: '#000',  inverseTextColor: '#fff',  noteFontSize: 14,  get defaultTextColor() {    return this.textColor;  },  // iPhoneX SafeArea  Inset: {    portrait: {      topInset: 24,      leftInset: 0,      rightInset: 0,      bottomInset: 34,    },    landscape: {      topInset: 0,      leftInset: 44,      rightInset: 44,      bottomInset: 21,    },  },};

React Native: I am useing date time picker from community and it is converting my time to GMT+0

$
0
0

I am on GMT+3 and when I use @react-native-community/datetimepicker. It converts my date automatically to the GMT+0. You can check my code below.Do someone now why it is converting?Thank you!

DATE TIME PICKER

<DateTimePicker   testID="dateTimePicker"   value={data[name]} // value={new Date()}   mode={type} // mode="time"   is24Hour={true}   display="spinner"   onChange={handleChange}   minimumDate={type === "date" ? new Date() : undefined} />

HANDLE CHANGE FUNCTION

const handleChange = (event: any, selectedDate: Date) => {setShow(false)console.log(selectedDate) // returns the selected date - 3 hoursif (selectedDate) {  setDate(formatDate(selectedDate, type))  setData({ ...data, [name]: selectedDate })}

}

Types for cardStyleInterpolator props

$
0
0

I am using this in my navigation stack:

<NavigationStack.Screen                    name="UserMenu"                    component={UserMenu}                    options={{                      headerShown: false,                      cardStyleInterpolator: forSlideFromLeft,                    }}                  />
const forSlideFromLeft = (props) => {  const { current, layouts } = props;  console.log('PROPS FROM USER MENU', current)  console.log('PROPS FROM USER MENU2', layouts)  const translateX = current.progress.interpolate({    inputRange: [0, 1],    outputRange: [-layouts.screen.width, 0],  });  if (props.index === 2) {    return {      cardStyle: {        transform: [{ translateX }],      },    };  } else {    return {};  }};

but I get an error on props that Parameter 'props' implicitly has an 'any' type. What could be it's type. If I infer from usagein VS Code, I get this:

(props: { index?: any; current?: any; layouts?: any; })

But I don't want to use anytypes. If I print the currentand layout values on the console, I get something like this:

current:

{progress: AnimatedInterpolation}progress: AnimatedInterpolation {_listeners: {…}, _children: Array(0), _parent: AnimatedValue, _config: {…}, _interpolation: ƒ, …}__proto__: Object

layout:

{screen: {…}}screen: {width: 411.4285583496094, height: 707.4285888671875}__proto__: Object

How can I fix this? What would be the suitable type to use here?

Viewing all 6214 articles
Browse latest View live