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

How can I access params in next navigation

$
0
0

I work with Typescript and I have simple navigation:

function go_to_screen(rout_name:string,device_model:string){  avis_instance.save_data('main_model', device_model);  navigation.navigate(rout_name,{ name: device_model });}

and then, on the next navigation I cannot access to name param via:

route.params.name or params.name ...

How can do this? Thanks!

P.S:here is component in next view : I generated it via default init expo .you can see what and how access to it .do you have any idea ?

export default function BottomTabNavigator() {  const colorScheme = useColorScheme();  return (<BottomTab.Navigator      initialRouteName="TabOne"      tabBarOptions={{ activeTintColor: Colors[colorScheme].tint }}><BottomTab.Screen        name=" "        component={TabOneNavigator}      /></BottomTab.Navigator>  );}const TabOneStack = createStackNavigator<TabOneParamList>();function TabOneNavigator() {  console.log("moziii"+route.params.name );  return (<TabOneStack.Navigator><TabOneStack.Screen        name="TabOneScreen"        component={TabOneScreen}        options={{ headerTitle: 'Anik' ,        headerStyle: {          backgroundColor: '#034ea2',        },        headerTintColor: '#fff',        headerTitleStyle: {          fontWeight: 'bold',        },      }}      /></TabOneStack.Navigator>  );}

How to correctly set an array of fetched objects to a state in react and render the data in a FlatList

$
0
0

I can't seem to find a way to correctly type my Interfaces and Array of Objects to use in a FlatList.

I am using ReactNative with Typescript.

The json file I fetched was from the NewsAPI which provides JSON data like this.

{"status": "ok","totalResults": 10,    -"articles": [        -{            -"source": {"id": null,"name": "somename"        },"author": "someauthor","title": "sometitle","description": "somedesc","url": "someurl","urlToImage": "someimage","publishedAt": "somedate",     },+{ … },    ]}

My current attempt looks like this but I can't wrap my head around the right method to use the keys for the renderItems and the keyExtractor of the FlatList.

interface IState {news: {    [key: string]: IArticles},loading: boolean}interface IArticles { //Since I don't actually want all the values of the object I left some out    title: string,    url: string,    urlToImage: string}export default class NewsField extends React.Component<{}, IState> {constructor(props: IProps) {    super(props);}state: IState = {    news: [],    loading: true}componentDidMount() {    this.fetchNews(); //This is where I set the state and fetch the data}render() {    return (<View><FlatList                data={this.state.news}                renderItem={({ item, index }) => {                    return (<View style={styles.containerList}><Text>{item.title}</Text></View>                    );                }}                keyExtractor={({ item, index }) => item.title.toString();}            /></View>    )}

How to get response data from Axios and map to the custom object

$
0
0

How I can map the response data object from axios to custom object? Here is the code below.Can I use map? As in, response.data.results.map?

   public getAllPromise(): Promise<any[]> {        return new Promise((resolve, reject) => {            axios.get('https://www.xxxx').then((response) => {                resolve(response.data.results);                console.log(response +' -----from service');            }).catch((error) => {                reject(error);            });        });    }

React Native Align button on top of keyboard for all devices

$
0
0

So I need to align a button Which is not at bottom om screen by design should be at middle of screen but it should align to be on top of the keyboard for all devices.

If you check this screenshot :

enter image description here

for Some devices I mange to do it, but in some others is not really aligned :

enter image description here

how can I manage this to work in all?

this is what I did so far :

<Padding paddingVertical={isKeyboardOpen ? Spacing.unit : Spacing.small}><Button      variant="solid"      label='Next'      style={styles.submitBtn}    /></Padding>

And isKeyboardOpen is just a method which will create a listner based on the platform return true if keyboard is open :

 Keyboard.addListener(  Platform.OS === 'ios' ? 'keyboardWillShow' : 'keyboardDidShow',  true  );

And submitBrn css class is :

submitBtn: {  margin: Spacing.base,},

How to fix Property 'incrementCount' does not exist on type 'ContextType | undefined'

$
0
0

I am trying to abstract the logic of useContext and useReducer to not repeat the code whenever i create a new context but i ran in to some problems when i try to strongly type createContext with typescript.

With this function i automate context creation:

import React, { createContext, ReactElement, useReducer } from 'react';type ProviderProps = {    children: ReactElement;};type ActionType = {  type: string;    payload?: any;};export default function <StateType>(    reducer: (state: StateType, action: ActionType) => StateType,    actions: any,    initialState: StateType,) {    type ContextType = {        state: StateType;        actions:{            [k: string]: Function;        }    };    const Context = React.createContext<ContextType | undefined>(undefined);    const Provider = ({ children }: ProviderProps) => {        const [state, dispatch] = useReducer(reducer, initialState);        const boundActions: any = {};        for (let key in actions) {            boundActions[key] = actions[key](dispatch);        }        return (<Context.Provider value={{ state, actions:{                ...boundActions            } }}>                {children}</Context.Provider>        );    };    return { Context, Provider };}

Example context creation:

import createDataContext from './createDataContext';import { INCRASE_COUNT, DECRASE_COUNT } from './ActionTypes';type ActionType = {    type: string;    payload?: any;};type StateType = {    count: number;};const reducer = (state: StateType, action: ActionType) => {    switch (action.type) {        case INCRASE_COUNT:            return { count: state.count + 1 };        case DECRASE_COUNT:            return { count: state.count - 1 };        default:            return state;    }};const incrementCount = (dispatch: React.Dispatch<any>) => {    return () => {        dispatch({ type: INCRASE_COUNT });    };};const decrementCount = (dispatch: React.Dispatch<any>) => {    return () => {        dispatch({ type: DECRASE_COUNT });    };};export const { Context, Provider } = createDataContext<StateType>(    reducer,    {        incrementCount,        decrementCount,    },    { count: 69 },);

When i use it:

import { Context as ExampleContext } from '../context/ExampleContext';const { state, actions } = useContext(    ExampleContext,);

it underlines state and actions with a red line and says:Property 'state, actions' does not exist on type 'ContextType | undefined'

What did i do wrong here is there something that i missed?

PLZZZZZZ HELP ME.

How to export SVG from a typescript custom package to React Native Project

$
0
0

I have a custom package called "app-packages", and i want all of my .png and .svg stored in this package. I manage to export the .png files but i have problems exporting and using the .svg file.

I already installedhttps://github.com/kristerkari/react-native-svg-transformer& https://github.com/react-native-svg/react-native-svg in my app-packages and react native app.

What i have tried:

I have src/Arrow.svg in the package, and i export it like this in src/index.tsx.

export { default as SvgPicture} from './Arrow.svg'

i already create a declaration.d.ts in src/

declare module "*.svg" {import React from 'react';import { SvgProps } from "react-native-svg";const content: React.FC<SvgProps>;export default content;}

here is my tsconfig.json

{"compilerOptions": {"target": "ESNext","module": "ESNext","strict": true,"outDir": "build","declaration": true,"jsx": "react","importHelpers": true,"moduleResolution": "node","experimentalDecorators": true,"esModuleInterop": true,"allowSyntheticDefaultImports": true,"noImplicitAny": false,"allowJs": false,"sourceMap": true,"lib": ["es6", "dom", "dom.iterable", "es2016", "es2017"],"forceConsistentCasingInFileNames": true,"resolveJsonModule": true,"isolatedModules": true,"noImplicitReturns": true,"noImplicitThis": true,"strictNullChecks": true,"suppressImplicitAnyIndexErrors": true,"noUnusedLocals": true,"noUnusedParameters": true,"noEmit": true},"include": ["src", "src/declaration.d.ts"],"exclude": ["node_modules", "build"]

}

after all that done, i build the package and tried it in my app.like this

import {SvgPicture} from 'app-packages';

and call it like this in render because i already installed react-native-svg-transformer

<SvgPicture />

but the result is this

Invariant Violation: View config getter callback for component `../../../Arrow.svg` must be a function (received `undefined`).

if the SVG file is in my react native app, the step above will show the .svg. But it will fail if i move it to app-packages. Anybody have a solution?

Unable to resolve module 'module://graphql/language/parser.js'

$
0
0

I am trying to make a React Native TypeScript project on Snack Expo. Although I have already added graphql in the package.json as well as the types file, I still get this error :

Device: (1:8434) Unable to resolve module 'module://graphql/language/parser.js'  Evaluating module://graphql/language/parser.js  Evaluating module://graphql-tag.js  Evaluating module://graphql/loadCountries.tsx.js  Evaluating module://App.tsx.js  Loading module://App.tsx

How can I fix this? I am not using an JS Files. Here's the link to the expo:

https://snack.expo.io/qYOFLsmjv

How to use react native's platform-specific extensions with typescript?

$
0
0

The problem:

I have a react native custom hook with platform specific code, which I need to import based on the platform. If I import it like import useWifi from 'hooks/use-wifi.android';, everything works fine (on android).

What I've tried:

Following rn's instructions for platform specific code, I have the following file structure

...hooks  ...  use-wifi.android.ts  use-wifi.ios.ts...

However, when I try to import it like import useWifi from 'hooks/use-wifi';, typescript type check does not pass, and I get this error in metro:

error: Error: Unable to resolve module `hooks/use-wifi` from `src/screens/home/index.tsx`: hooks/use-wifi could not be found within the project.

I've added a use-wifi.d.ts file with

export * from './use-wifi.android';export * from './use-wifi.ios';

This allows tsc to pass, but metro still fails to bundle.

I guess I could have a single hooks/use-wifi.ts file and make the code split there, but I'd rather do it this way if possible.


TypeError: _fakeTimers(...).LegacyFakeTimers is not a constructor

$
0
0

When running tests in a react-native Typscript based application i get a log full of the following errors:

FAIL  src/__test__/storeLayer.test.tsx● Test suite failed to run    TypeError: _fakeTimers(...).LegacyFakeTimers is not a constructor      at new NodeEnvironment (node_modules/jest-environment-node/build/index.js:123:23)

All able about it (and was solved) pointed to jest-environment-jsdom, but we not use it, and do not plan to use it, so any ideas where to look at?

Thanks

How to use SVG in Expo SDK 40 React Native with TypeScript?

$
0
0

I tried to use a svg in expo sdk 40 width : react-native-svg-transformer

Here is the process i followed :

I got an error saying : it was expected string type but received a number

Before the SDK 40, the process was workingThanks for Help !

All styled components return any (@types/styled-components)

$
0
0

I'm having a weird issue when using styled-components along with VSCode. Below is basically what I get for any components coming from styled-components, they all return any.

enter image description hereenter image description here

I got it working before, but can't tell when and I can't see what's wrong in the setup to return any for all the components. I tried to move back to tslint config, removing/commenting out all rules inside the eslintrc files, but couldn't make it work either.

Supprisingly enough, I tried the starter kit I'm using for my project and the types there are working with the original setup.

enter image description here

I tried to use the same version of styled-components packages, but still couldn't make it work. Any help, or direction to look at this issue would be very welcomed!

.eslintrc.js

module.exports = {  env: {    browser: true,    es6: true,  },  extends: ['plugin:@typescript-eslint/recommended','plugin:@typescript-eslint/recommended-requiring-type-checking','plugin:react/recommended','prettier/@typescript-eslint',  ],  parser: '@typescript-eslint/parser',  parserOptions: {    project: './tsconfig.json',    sourceType: 'module',    ecmaFeatures: { jsx: true },  },  plugins: ['@typescript-eslint', 'react', 'react-native'],  rules: {    camelcase: 'off','react/display-name': 'off','react/prop-types': 'off','@typescript-eslint/ban-ts-ignore': 'off','@typescript-eslint/camelcase': 'off','@typescript-eslint/explicit-function-return-type': 'off','@typescript-eslint/interface-name-prefix': 'off','@typescript-eslint/no-explicit-any': 'off','@typescript-eslint/no-use-before-define': 'off','@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_' }],'@typescript-eslint/no-non-null-assertion': 'off','@typescript-eslint/unbound-method': 'off','@typescript-eslint/no-unsafe-assignment': 'off','@typescript-eslint/no-unsafe-call': 'off','@typescript-eslint/no-unsafe-member-access': 'off','@typescript-eslint/no-unsafe-return': 'off','@typescript-eslint/no-misused-promises': ['error',      {        checksVoidReturn: false,      },    ],'@typescript-eslint/explicit-module-boundary-types': ['error', { allowArgumentsExplicitlyTypedAsAny: true }],  },  settings: {    react: {      pragma: 'React',      version: 'detect',    },  },  ignorePatterns: ['node_modules/**/*', 'docs/**/*', 'examples/**/*', 'lib/**/*'],};

tsconfig.json

{"compilerOptions": {"allowSyntheticDefaultImports": true,"baseUrl": "./src","experimentalDecorators": true,"inlineSources": true,"jsx": "react","lib": ["es2017", "dom"],"module": "commonjs","moduleResolution": "node","noEmit": true,"noUnusedLocals": true,"noUnusedParameters": true,"plugins": [      {"name": "typescript-styled-plugin","lint": {"validProperties": ["shadow-color","shadow-opacity","shadow-offset","shadow-radius","padding-horizontal","padding-vertical","margin-vertical","margin-horizontal","tint-color","aspect-ratio","elevation"          ]        }      }    ],"resolveJsonModule": true,"skipLibCheck": true,"sourceMap": true,"sourceRoot": "./src","strict": true,"strictPropertyInitialization": false,"suppressImplicitAnyIndexErrors": true,"target": "es2015"  },"include": [".eslintrc.js", "src/**/*.ts", "src/**/*.tsx"]}
"lint": "yarn format && yarn eslint && yarn stylelint","eslint": "tsc -p . --noEmit --skipLibCheck; eslint --fix 'src/**/*.{ts,tsx}'",..."@typescript-eslint/eslint-plugin": "3.8.0","@typescript-eslint/parser": "3.8.0","eslint": "7.6.0","eslint-config-prettier": "6.11.0","eslint-plugin-react": "7.20.5","eslint-plugin-react-native": "3.8.1",

styled.d.ts

import 'styled-components';declare module 'styled-components' {  // tslint:disable-next-line  export interface DefaultTheme {    darkMode: boolean;    background: string;    lightBackground: string;    grayBackground: string;    darkBackground: string;    heading: string;    subheading: string;    copy: string;    stroke: string;    underlay: string;    map: string;  }}

How to use the same component in different screens in a navigator with typescript?

$
0
0

In my React Native (Expo) app I want to have a FriendsScreen and a OthersScreen in a MaterialTopTabNavigator. It's kind of a social media app. All of the user's friends are displayed in a list on the FriendsScreen. The OthersScreen shows users who have not yet been added as friends. However, since the two screens look almost the same, I wanted to use the same component for both screens (To reuse code and not have to copy and paste code when making changes).

That's why my navigator looks like this:

import { createMaterialTopTabNavigator } from '@react-navigation/material-top-tabs';const TopTab = createMaterialTopTabNavigator<TopTabParamList>();export default function TopTabNavigator() {    return (<TopTab.Navigator><TopTab.Screen name="Friends" component={UsersScreen} /> // Friends: UsersScreen<TopTab.Screen name="Others" component={UsersScreen} /> // Others: UsersScreen</TopTab.Navigator>    );}

In order to be able to display small differences between the two screens, I wanted to give the UserScreen a route param named type.

export type TopTabParamList = {  Friends: { type: 'Friends' | 'Others' };  Others: { type: 'Friends' | 'Others' };};

In the UsersScreen I want to use the type param to determine whether the UsersScreen should fetch the friends of the user or strangers from my server. But since I'm using Typescript, I don't know how to type the route prop.

interface Props {  route: RouteProp<TopTabParamList, /*'Friends' or 'Others'?*/>;}

Somehow I have the feeling that my problem should be solved differently...

Final question:

How can I have 2 tabs (screens) in a MaterialTopTabNavigator that use the same component in which I can determine which screen this component now represents, while everything is correctly typed with Typescript?

Understanding react-native init template and files: What are all these files?

$
0
0

Today I started to play around with a fresh React Native project. I ran the basic react-native init command and got the sample project littered with all these weird files. Are all of these necessary and what are they?


.buckconfig

This seems to be related to a RN build tool called "Buck" made by Facebook. Is this used by default in the freshly initialise project? How can I check what builder is being used?


.flowconfig

Never heard of this before. Short googling gave me the understanding that this is some sort of type checker for JS. I am using TypeScript, so I think there's no need for this config file to be present?


.watchmanconfig

Empty watchmanconfig in the project root? Why? What's the point in having this there?

Edit: Apparently it is safe to delete from the project as long as it is not too large

Do I need to keep .watchmanconfig file in react-native project?


babel.config.json

Then probably the most confusing of them all for me was surprisingly Babel config. Babel has been present in many projects I have been working on. Always they have been some already initialised projects and I have never needed to pay much attention to the configuration details - hence this post. If using TypeScript and tsc, what do we need Babel for? Isn't tsc already transpiling the TypeScript code?


For a test I deleted all of the above files from my test project and it still seems to build and work just fine. I am now thinking that could this lead to some problems later in the development?

I like to keep my projects as clean as possible from all trash, so they are nicer to develop and easier to understand as there are less random stuff floating around.

How to create dynamic React Native components

$
0
0

I want the button to be dynamically created and used when the click event occurs. The button's creation location should be created 10px to the right of the existing button. Ask for help from great and kind friends.

How to redefine prop for React class

$
0
0

I´m using Avatar from react-native-elements and the ImageComponent prop is typed as React.ComponentClass (IntelliSense report type React.ComponentClass<{}, any>)

When using a functional component (with prop key) I get red squiggles under ImageComponent:

<Avatar    rounded    size={c.styles.avatarSize}    containerStyle={{ margin: c.styles.marginLRTB / 2 }}    placeholderStyle={{ backgroundColor: colors.background }}    ImageComponent={() => AvatarImage(key)}  />

Type '() => JSX.Element' is not assignable to type 'ComponentClass<{}, any>'.ts(2769)

AvatarImage:

  const AvatarImage = (key: string) => (<FastImage      style={{ width: '100%', height: '100%' }}      source={sourcesState[key].category === 'In-app' ? avatars[key as QuotesListKeys] : { uri: sourcesState[key].imageUrl }}    />  );

How can I fix this typescript error? I´m still learning typescript and need some help with this one.

I´ve tried to define a new class/interface that extend Avatar/AvatarProps:

  type MyAvatarProps = Omit<AvatarProps, 'ImageComponent'> & { ImageComponent: FC<{ key: string }> };  class MyAvatar extends Avatar<MyAvatarProps> {}

I get typescript error Type 'Avatar' is not generic.ts(2315)

How do I extend Avatar with MyAvatarProps when it's not generic?

Or is there other/better ways to handle this?


Expo + FirebaseAuthentication (with Twitter) doesn't work by error

$
0
0

I want to construct FirebaseAuthentication with Twitter using Expo.But an error that the request token is invalid occurred.

Running server side program with my PC and Expo(client) side program with Expo app in my iPhone.

(* is each token and so on)

Server side (JavaScript)

const bodyParser = require('body-parser');const fetch = require('node-fetch');const OAuth = require('oauth-1.0a');const qs = require('qs')const HmacSHA1 = require('crypto-js/hmac-sha1')const Base64 = require('crypto-js/enc-base64')const port = process.env.PORT || 3000const config = {  GOOGLE: {    CLIENT_ID: "",    CLIENT_SECRET: "",  },  GITHUB: {    CLIENT_ID: "",    CLIENT_SECRET: "",  },  TWITTER: {    CLIENT_ID: "*****",    CLIENT_SECRET: "*****",  }}const app = express();app.use(bodyParser.urlencoded({ extended: true }));app.use(bodyParser.json());app.post('/auth/google', async (req, res) => {  async function createTokenWithGoogleCode(code, redirect_uri) {    const url = `https://www.googleapis.com/oauth2/v4/token`    const res = await fetch(url, {      method: 'POST',      body: JSON.stringify({        code,        client_id: config.GOOGLE.CLIENT_ID,        client_secret: config.GOOGLE.CLIENT_SECRET,        redirect_uri,        grant_type: 'authorization_code'      })    });    return await res.json()  }  return res.json(await createTokenWithGoogleCode(req.body.code, req.body.redirect_uri))});app.post('/auth/github', async (req, res) => {  async function createTokenWithGithubCode(code) {    const url =      `https://github.com/login/oauth/access_token` +      `?client_id=${config.GITHUB.CLIENT_ID}` +      `&client_secret=${config.GITHUB.CLIENT_SECRET}` +      `&code=${code}`;    const res = await fetch(url, {      method: 'POST',      headers: {        Accept: 'application/json','Content-Type': 'application/json',      },    });    return await res.json()  }  return res.json(await createTokenWithGithubCode(req.body.code))});app.post('/auth/twitter/request_token', async (req, res) => {  const { redirect_uri } = req.body  const oauth = OAuth({    consumer: {      key: config.TWITTER.CLIENT_ID,      secret: config.TWITTER.CLIENT_SECRET,    },    signature_method: 'HMAC-SHA1',    hash_function: (baseString, key) => Base64.stringify(HmacSHA1(baseString, key))  })  const request_data = {    url: 'https://api.twitter.com/oauth/request_token',    method: 'POST',    data: {       oauth_callback: redirect_uri,    }  };  const response = await fetch(request_data.url, {    method: request_data.method,    headers: oauth.toHeader(oauth.authorize(request_data))  })  const text = await response.text();  return res.json(qs.parse(text))});app.post('/auth/twitter/access_token', async (req, res) => {  const { oauth_token, oauth_token_secret, oauth_verifier } = req.body  const oauth = OAuth({    consumer: {      key: config.TWITTER.CLIENT_ID,      secret: config.TWITTER.CLIENT_SECRET,    },    signature_method: 'HMAC-SHA1',    hash_function: (baseString, key) => Base64.stringify(HmacSHA1(baseString, key))  })  const request_data = {    url: 'https://api.twitter.com/oauth/access_token',    method: 'POST',    data: {      oauth_verifier,      },  }  const headers = oauth.toHeader(oauth.authorize(request_data, {key: oauth_token, secret: oauth_token_secret}))  const response = await fetch(request_data.url, {    method: request_data.method,    data: request_data.data,    headers  })  if (response.status !== 200) {    res.status = response.status    return res.json({message: "something wrong"})  }  const text = await response.text();  return res.json(qs.parse(text))})if (!module.parent) {  app.listen(3000, () => {    console.log('Example app listening on port 3000!');  });}module.exports = app;Expoexpo init expo && cd $_yarn add firebase

Expo side (TypeScript)

import React from 'react'import { StyleSheet, Text, Button, View } from 'react-native'import { Facebook } from 'expo';import * as AuthSession from "expo-auth-session"import firebase from 'firebase';const AUTH_BASE_URL = "http://localhost:3000"const REDIRECT_URL = AuthSession.getRedirectUrl();const FACEBOOK_APP_ID = ""const GOOGLE_CLIENT_ID = ""const GITHUB_CLIENT_ID = ""if (!firebase.apps.length) {  firebase.initializeApp({    apiKey: "*****",    authDomain: "*****",    databaseURL: "*****",    projectId: "*****",    storageBucket: "*****",    messagingSenderId: "*****"  })}async function createTokenWithCode(provider, code) {  const url = `${AUTH_BASE_URL}/auth/${provider}/`  console.log(url)  const res = await fetch(url, {    method: 'POST',    headers: {'Accept': 'application/json','Content-Type': 'application/json',    },    body: JSON.stringify({      code,      redirect_uri: REDIRECT_URL // Google で必要    })  })  const json = await res.json();  console.log(json)  return json}async function getTwitterRequestToken() {  const url = `${AUTH_BASE_URL}/auth/twitter/request_token`  const res = await fetch(url, {    method: 'POST',    headers: {'Accept': 'application/json','Content-Type': 'application/json',    },    body: JSON.stringify({      redirect_uri: REDIRECT_URL    })  });  return await res.json();}async function getTwitterAccessToken(params) {  const { oauth_token, oauth_token_secret, oauth_verifier } = params  const url = `${AUTH_BASE_URL}/auth/twitter/access_token`  const res = await fetch(url, {    method: 'POST',    headers: {'Accept': 'application/json','Content-Type': 'application/json',    },    body: JSON.stringify({ oauth_token, oauth_token_secret, oauth_verifier })  });  return await res.json();}export default class App extends React.Component {  constructor(props) {    super(props)    this.state = {      user: null    }    firebase.auth().onAuthStateChanged((user) => {      if (user) {        this.setState({ user: user.toJSON() })        console.log(user)      } else {        this.setState({ user: null })      }    })  }  handleLogout() {     firebase.auth().signOut()  }  async handleTwitterLogin() {    const { oauth_token, oauth_token_secret } = await getTwitterRequestToken()    const { params }  = await AuthSession.startAsync({      authUrl: `https://api.twitter.com/oauth/authenticate?oauth_token=${oauth_token}`    });    const oauth_verifier = params.oauth_verifier    const result = await getTwitterAccessToken({oauth_token, oauth_token_secret, oauth_verifier})    const credential = firebase.auth.TwitterAuthProvider.credential(      result.oauth_token,       result.oauth_token_secret    )    firebase.auth().signInAndRetrieveDataWithCredential(credential);  }  render() {    return (<View style={styles.container}><Text>Firebase Authentication Example</Text><Button onPress={this.handleTwitterLogin} title="Twitter" /><Button onPress={this.handleLogout} title="Logout" /><Text>displayName: {this.state.user && this.state.user.displayName}</Text><Text>providerId: {this.state.user && this.state.user.providerData[0].providerId}</Text></View>    );  }}const styles = StyleSheet.create({  container: {    flex: 1,    backgroundColor: '#fff',    alignItems: 'center',    justifyContent: 'center',  },});

I referred to following page.https://qiita.com/okamuuu/items/6da12f295c3b8a7bc3d8

Please tell me the solution.

I'm sorry if I can't make you understood.

Call Functional Component Statically from another component

$
0
0

After spending hours to figure out how I can call a function Statically from another functional component in react-native. I Have a component called SnackbarFC and I would like to call it by doing so when the button is pressed:

    SnackBar.show({      message: ArabicPlaceholders.Copy,      autoHide: true,      copyStyle: true,      color: '#484848'    })

To get there I created an Interface:

type ISnackbar = {show: (options: SnackbarOptions) => void;}

then

type SnackbarOptions = {    color?: string    onPress?: () => void    onLongPress?: () => void    message?: string    pressable?: boolean    copyStyle?: boolean    autoHide?: boolean}

After that I do

    show(options: SnackbarOptions) {        console.log("options", options);        return (<SnackbarFC                color={options.color}                message={options.message}                onPress={options.onPress}                onLongPress={options.onLongPress}                pressable={options.pressable}                autoHide={options.autoHide}                copyStyle={options.copyStyle}            />        );    }}

and finally, this how the component looks like

export const SnackbarFC = (props: SnackbarOptions) => {    const animation = useRef(new Animated.Value(0)).current;    const fadeIn = () => {        Animated.timing(animation, {            toValue: 1,            duration: 800,            useNativeDriver: true        }).start();    }.....

I do get the options when i do `console.log("options", options);``but the SnackbarFC is not fired, so if I add a log inside this component nothing happens.

I really appreciate it if anyone could help me to figure out the problem :(

Thanks in advance :)

VS Code eslint underlining wrong errors

$
0
0

Problem

eslint is underlining errors incorrectly in my React Native files.

Here is one example of a file that has incorrect errors. In this example it is saying cannot find name source even though that is an accepted prop by Image in React Native.

Does anyone have any advice on how to fix this?

ScreenError

React-Native create button when other button's onPress Event

$
0
0

I want the button to be dynamically created and used when the onPress event occurs. Ask for help from great and kind friends.

I want{ in screen one Button , -> Button click -> create one Button -> so we have two button }

it is my code

import React, { Component } from 'react'import { Button } from 'react-native'const Test = () => {     return( <Button title='test' onPress={<Button title='test1'/>}/>     ) } export default Test 

or

import React, { Component } from 'react'import { Button } from 'react-native'const Test = () => {     return( <Button title='test' onPress={ButtonRender}/>     ) }const ButtonRender =():any=>{    return <Button title='test1'/>}export default Test 

I have a problem. It is not created Button. I need help

how to use cordova background in ionic + react project?

$
0
0

I need my app to repeatedly execute sendLocation function in the background.

App.tsx

import React from 'react';import { IonApp } from '@ionic/react';import { sendLocation } from './Util/location'const App: React.FC = () => ( <IonApp>      {setInterval(() => sendLocation(), 2000)}</IonApp>);export default App;

I tried this but I couldn't apply it to react:https://www.techiediaries.com/ionic-background-mode/

Viewing all 6287 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>