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

react-native-open-maps with iOS

$
0
0

I am using openMap to open a map in my react native project. When I run it in iOS simulator, it opens on Apple Maps.

On a real phone, will it still open Apple Maps or will it open Google Maps if installed? On IOS


Can't render elements from mutated Array - React

$
0
0

So, the problem I've faced is that when I click delete button at any index it just deletes last elementfor example, if I press first delete button, it should remove first input and the delete button, but what it does is that it deletes last element only... What could be wrong?

function App() {  const [names, setNames] = React.useState(["First","Second","third","fourth"  ]);  const onChange= (index: number, editedName: string) => {    const mutatedNames = [...names];    mutatedNames[index] = editedName;    setNames(mutatedNames);  };  function onDelete(index: number) {    const nameArr = [...names];    nameArr.splice(index, 1);    setNames(nameArr);  }  return (<div>      {names.map((name, index) => (<ChildComponent          key={index}          name={name}          index={index}          onChange={onChange}          onDelete={onDelete}        />      ))}</div>  );}const Child = React.memo(  ({ name, index, onChange, onDelete }) => {    return (<div><input          onChange={(event) => onChange(index, event.target.value)}        /><button onClick={() => onDelete(index)}>delete</button></div>    );  });

React Native/Typescript - Error Module '"react-native"' has no exported member 'Pressable'.ts(2305)

$
0
0

I cannot seem to remove this error message and don't know exactly where it comes from. Pressable is indeed a working component, but the thing that shouts at me doesn't understand that. What is it and how to fix it?

I tried updating react and react-native versions to latest, also tried upgrading typescript version to latest and still the error persists (the code runs fine though).

This is what it looks like if I'm unclear

Why does the string come as an object React Native?

$
0
0

I draw a string value through api and I want to print it in View. But the incoming string value comes as Promise. How can I prevent this?

"Invariant Violation: Objects are not valid as a React child (found: object with keys {_40, _65,_55, _72}=. If you meant to render a collection of children, use an array instead."

async getTitle(id) {            try {        const username = await AsyncStorage.getItem('username');        const token = await AsyncStorage.getItem('token');                    if(token) {            var credentials = Base64.btoa(username +':'+ token);            var URL         = `https://portal.xxxxx.com/api/v1/User/${id}`;            var title = await axios.get(URL, {headers : { 'Espo-Authorization' : credentials }})            .then((res) => {                return <Text>{res.data.title}</Text>            })            .catch((err) => {                console.log(err);            });            return title;        }    }catch (err) {        console.log(err);    }}<List    contentContainerStyle={styles.listContentContainer}    data={stream}    ItemSeparatorComponent={Divider}    renderItem={({ item, index }) => (        item.type === "Post" ?<ListItem            key={index}            title={<Text><Text style={{ fontSize: 12 }}>{item.createdByName}</Text> {this.getTitle(item.createdById)} {'\n'} <Text style={{ fontSize: 12 }}>{Moment(item.createdAt).add(3, 'hours').format('lll')}</Text>{'\n'}<Text style={{ fontSize: 12 }} status="warning">{this.statusLanguage(status)}</Text></Text>}            description={<Text style={{ fontSize: 15 }}>{item.post}</Text>}            accessoryLeft={renderCommentIcon}        /> : null    )}/>

React navigation V5 header button usage

$
0
0

I have react navigation screen as follows .

<Stack.Screen name="Home" component={HomeScreen} />

I need to navigate another screen using a right header button how can i do this.I'am using react navigation V5

React Native : how to configure webpack, which loader should I add?

$
0
0

My React Native app contains a Video component from ReactXP library. My app doesn't contain a lot of code, there is only 3 important files -> App.tsx which contains a VideoContainer component (VideoContainer.tsx) and VideoContainer contains a VideoComponent (VideoComponent.tsx). My VideoComponent returns the RX.Video component.

Here is my problem, when I try to start my app on web with "npm run start:web" I get the following error :

ERROR in ./Video/VideoContainer.tsx 5:28Module parse failed: Unexpected token (5:28)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| import {VideoProps} from "./VideoPropsInterface"|> export const VideoContainer : React.FC<VideoProps> = ( {id, src} : VideoProps ) => <VideoComponent id={id} src={src}></VideoComponent>i 「wdm」: Failed to compile.No type errors found

So I check on internet what is a loader because I'm a beginner in webpack and it exists different loaders such as file-loader, url-loader, ts-loader, etc ...But I don't know which one I need to add in my project, I try different loaders but no one seems to work.

Here is my initial code :

App.tsx

import React, { ReactElement } from 'react';import RX from 'reactxp';import {VideoContainer} from "../Video/VideoContainer";const _styles = {  main: RX.Styles.createViewStyle({    justifyContent: 'center',    alignItems: 'center',    flex: 1,  }),  title: RX.Styles.createTextStyle({    fontWeight: 'bold',    fontSize: 36,    textAlign: 'center',  }),  label: RX.Styles.createTextStyle({    marginTop: 10,    textAlign: 'center',    fontSize: 16,  }),  name: RX.Styles.createTextStyle({    fontWeight: 'bold',    fontSize: 36,    color: '#42B74F',  }),  links: RX.Styles.createViewStyle({    justifyContent: 'center',    flexDirection: 'row',    alignItems: 'center',    marginTop: 10,  }),  link: RX.Styles.createLinkStyle({    marginRight: 5,    marginLeft: 5,    color: '#0070E0',  }),};export default class App extends RX.Component {  constructor(props : any ){    super(props);  }  public render(): ReactElement<RX.View> {    return (<RX.View style={ _styles.main }><VideoContainer id="videoPlayer" src={"http://clips.vorwaerts-gmbh.de/VfE_html5.mp4"}></VideoContainer><RX.View><RX.Text style={ _styles.title }>Welcome to <RX.Text style={ _styles.name }>ReactXP</RX.Text></RX.Text><RX.Text style={ _styles.label }>To get started, edit /src/App.tsx</RX.Text></RX.View><RX.View style={ _styles.links }><RX.Link url={ 'https://github.com/Microsoft/reactxp' } style={ _styles.link }>GitHub</RX.Link><RX.Link url={ 'https://microsoft.github.io/reactxp' } style={ _styles.link }>Docs</RX.Link><RX.Link url={ 'https://github.com/Microsoft/reactxp/tree/master/samples' } style={ _styles.link }>Samples</RX.Link><RX.Link url={ 'https://github.com/Microsoft/reactxp/tree/master/extensions' } style={ _styles.link }>Extensions</RX.Link></RX.View></RX.View>    );  }}

VideoContainer.tsx

import {VideoComponent} from "./VideoComponent"import React from "react"import {VideoProps} from "./VideoPropsInterface"export const VideoContainer : React.FC<VideoProps> = ( {id, src} : VideoProps ) => <VideoComponent id={id} src={src}></VideoComponent>

VideoComponent.tsx

import React from 'react';import { View } from "react-native";import Video from 'reactxp-video'import {VideoProps} from "./VideoPropsInterface"export const VideoComponent: React.FC<VideoProps>= ( {id, src} : VideoProps) => {    return(<View nativeID={id}><Video source={src} /></View>    )}

Considered solution

I modified my VideoContainer.tsx code to check if the problem comes from typing with typescript. So I just take off the React.FC type of my VideoComponent constant.Here is the new code :

import {VideoComponent} from "./VideoComponent"import React from "react"import {VideoProps} from "./VideoPropsInterface"export const VideoContainer = ( {id, src} : VideoProps ) => <VideoComponent id={id} src={src}></VideoComponent>

Now I got the same error but location changes:

ERROR in ./Video/VideoContainer.tsx 5:42Module parse failed: Unexpected token (5:42)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| import {VideoProps} from "./VideoPropsInterface"|> export const VideoContainer = ( {id, src} : VideoProps ) => <VideoComponent id={id} src={src}></VideoComponent>i 「wdm」: Failed to compile.

Now it's unexpected token (5:42) and it corresponds to the second type VideoProps. So I think there is a problem with typescript, I think I need to add the ts-loader but once added, nothing change.

But I don't fully understand how webpack works. I try to create a webpack.config.js inside my web folder, and also isnide the web/webpack folder and in root directory but nothing changes.

Here is the content of my webpack.config.js :

const path = require('path');module.exports = {  entry: './src/index.ts',  module: {    rules: [      {        test: /\.tsx?$/,        use: 'ts-loader',        exclude: /node_modules/,      },    ],  },  resolve: {    extensions: [ '.tsx', '.ts', '.js' ],  },  output: {    filename: 'bundle.js',    path: path.resolve(__dirname, 'dist'),  },};

Here is my package.json :

{"name": "winversion","private": true,"main": "index.js","version": "0.0.1","scripts": {"rn-cli": "node scripts/react-native.js","start:android": "npm run rn-cli -- run-android","start:windows": "npm run rn-cli -- run-windows","start:ios": "npm run rn-cli -- run-ios","start:web": "cross-env platform=web webpack-dev-server --config=web/webpack/dev.js --progress --colors --mode=development","start:rn-dev-server": "npm run rn-cli -- start --reset-cache","build:web": "cross-env platform=web webpack --config=web/webpack/prod.js --progress --colors --mode=production","test": "jest -c jest/jest.config.js","test:watch": "npm run test -- --watch","test:debug": "node --inspect-brk node_modules/.bin/jest -c jest/jest.config.js --runInBand","build:types": "tsc --emitDeclarationOnly","type-check": "tsc --noEmit","type-check:watch": "npm run type-check -- -w","lint": "eslint --config .eslintrc --ext .ts,.tsx src"  },"devDependencies": {"@babel/core": "7.10.2","@babel/plugin-proposal-decorators": "7.10.1","@babel/preset-env": "7.10.2","@babel/preset-react": "^7.12.1","@react-native-community/cli": "1.11.2","@types/enzyme": "3.10.5","@types/jest": "25.2.3","@types/react": "^16.9.52","@types/react-native": "^0.63.25","@typescript-eslint/eslint-plugin": "3.2.0","@typescript-eslint/parser": "3.2.0","babel-loader": "8.1.0","compression-webpack-plugin": "4.0.0","cross-env": "7.0.2","enzyme": "3.11.0","enzyme-adapter-react-16": "1.15.2","enzyme-to-json": "3.5.0","eslint": "6.1.0","eslint-loader": "4.0.2","eslint-plugin-jest": "23.13.2","eslint-plugin-react": "7.20.0","eslint-plugin-reactxp": "0.1.10","fork-ts-checker-webpack-plugin": "4.1.6","html-webpack-plugin": "^4.3.0","jest": "26.0.1","metro-react-native-babel-preset": "0.59.0","react-dom": "^16.13.1","react-native-typescript-transformer": "^1.2.13","react-native-web": "^0.14.1","rnpm-plugin-windows": "0.6.1","ts-loader": "^8.0.5","typescript": "^3.9.5","url-loader": "^4.1.1","webpack": "^4.43.0","webpack-cli": "^3.3.11","webpack-dev-server": "^3.11.0","webpack-merge": "4.2.2"  },"dependencies": {"@types/react-native-video": "^5.0.3","babel-preset-es2015": "^6.24.1","oneplayerjs": "file:oneplayerjs-1.1.0.tgz","react": "16.13.1","react-native": "^0.59.10","react-native-video": "^5.1.0-alpha8","react-native-windows": "0.59.0-rc.3","reactxp": "2.0.0","reactxp-video": "^2.0.0"  }}

What is wrong with my code ?

Thanks for reading :)

How to test React native Hooks component - JEST & React Native testing Library

$
0
0

I am trying to test my react native hooks component, I am able to access/test use state variable but not able to test arrow methods in my functional component, kindly provide some suggestions.Attached sample code and test

interface IProps {  previousSceneName?: string,  selectedTab?: number,}type Props = IPropsexport default function LoginComponent(props: IProps) {  var [userName, setUserName] = useState("")  var [password, setPassword] = useState("")  const _userName = (text: string) => {    setUserName(text)    setUserNameError("")  }  const _setPassword = (text: string) => {    setPassword(text)    setPasswordError("")  }  const _isValidationPassed = () => {    if (userName.length === 0 && password.length === 0) {       setUserNameError(Errors.requiredMsg);       setPasswordError(Errors.requiredMsg);       return false     }    else if (userName.length === 0) { setUserNameError(Errors.requiredMsg); return false }    else if (password.length === 0) { setPasswordError(Errors.requiredMsg); return false }    else return true  }  const _userLogin = () => {    if (_isValidationPassed()) {      return true    }    return false;  }  return (<View><CustomTextfield        viewStyle= { style.textFieldView }        placeHolderColor = { Colors.orderStatusColor }        selectionColor = { Colors.darkBlue }        label = { "Username"}        isMandatory = { true}        placeholder = { General.userNamePlaceholder }        errorMsg = { userNameError }        onChangeText = { _userName }        value = { userName }        style = {{ textTransform: "none", width: '100%' }}        maxLength = { 50}        autoCapitalize = { "none"}        autoCompleteType = { "off"}        autoCorrect = { false}        testID = "Username"      /><CustomTextfield        secureTextEntry        // @ts-ignore        viewStyle = { style.textFieldView }        // @ts-ignore        // labelTextStyle={style.customLabelView}        placeHolderColor = { Colors.orderStatusColor }        label = { "Password"}        selectionColor = { Colors.darkBlue }        isMandatory = { true}        placeholder = { General.passwordPlaceholder }        errorMsg = { passwordError }        onChangeText = { _setPassword }        value = { password }        style = {{ textTransform: "none", width: '100%' }}        maxLength = { 50}        autoCapitalize = { "none"}        autoCompleteType = { "off"}        autoCorrect = { false}        testID = "Password"      /><Button testID="loginSubmit" onPress = { _userLogin } full style = { style.bottomButton } ><Text style={ style.buttonText1 }> GET STARTED </Text></Button></View>)}

My test file is(Commented code i am using to test that function),kinldy provide answers for testing the _isValidationPassed and _userLogin methods

describe("Test Hooks", () => {  let props: any;  let wrapper3: any;  // const _userLogin = jest.fn();  let wrapper1;  const tree = renderer.create(<Provider store={store}><LoginComponent /></Provider>    )  it("should render without throwing an error", () => {    expect(tree.toJSON()).toMatchSnapshot();  });  // beforeEach(() => {  //     const wrapper = mount(<Provider store={store}>  //         <LoginComponent _userLogin={_userLogin} />  //     </Provider>);  //     wrapper.find('Button[testID="loginSubmit"]').simulate('click');  // });  it("includes two paragraphs", () => {    const wrapper = mount(<Provider store={store}><LoginComponent /></Provider>    );    expect(wrapper.find("CustomTextfield")).toHaveLength(2);    expect(wrapper.find("Button")).toHaveLength(3);    expect(wrapper.find('Button[testID="loginSubmit"]')).toHaveLength(1);  });  // beforeEach(() => {  //     wrapper1 = shallow(<Provider store={store}>  //         <LoginComponent _isValidationPassed={_isValidationPassedTest} />  //     </Provider>);  // });  beforeEach(() => {    jest.spyOn(console, "warn").mockImplementation(() => {});  });  test("should have the login enabled with valid values", async () => {    const { getByTestId } = render(<Provider store={store}><LoginComponent /></Provider>    );    const wrapper1 = mount(<Provider store={store}><LoginComponent /></Provider>    );    fireEvent.changeText(getByTestId("Username"), "abdul");    expect(getByTestId("Username").props.value).toEqual("abdul");    fireEvent.changeText(getByTestId("Password"), "1234");    expect(getByTestId("Password").props.value).toEqual("1234");    //fireEvent.press(getByTestId("loginSubmit"));    //expect(result.current).toBe(now);    //expect(mockFn).toBeCalledTimes(1);  });});

Typing accessibilityRole

$
0
0

Using accessibilityRole in react native do I have to type out all the possible strings or is there an import that I can use?

createAccessibilityRole(parent: Element): string {  if(isLink) return 'link'  return 'text'}

Obviously the above doesn't work so I was wondering if we could import the type class or if we have to code it ourselves?


Change language based on user selection on expo

$
0
0

Just wondering if there's any way to change the language of an expo app with typescript based on user selection (so not device language).I read through the docs on expo https://docs.expo.io/versions/latest/sdk/localization/ but there doesn't seem to be anything on it.

Below is what I have currently, and it's only working for device set language.

import * as Localization from 'expo-localization';import I18n from 'i18n-js';// import translationsimport en from './en.json'import zh from './zh.json'// bind translations to i18nI18n.translations = {  en,  zh}// set phones languageconst getLanguage = async() => {  try {    const choice = Localization.locale    I18n.locale = choice.substr(0, 2)    I18n.initAsync()  } catch (error) {    console.log(error)  }}getLanguage()// export functionexport function t(name: string) {  return I18n.t(name)}

Only thing now is that I don't know how to pass a language based on user input.

React-Native-Reanimated and React-native

$
0
0

After creating minimal react-native app with expo and typescript i got a lot of strange errors:

  1. App working on web but crashes with android.Web app I`m getting expo error on my Xiaomi S2.S2 screen log.

There is a code i'm starting (in final without router):

import React from 'react';import { Button, StyleSheet, View  } from 'react-native';const styles = StyleSheet.create({    box: {        width: '50px',        height: '50px',        backgroundColor: '#000000'    }})export const SignInScreen = (): JSX.Element => {    // const offset = useSharedValue(0);    // const animatedStyles = useAnimatedStyle(() => {    //   return {    //     transform: [{ translateX: offset.value * 255 }],    //   };    // });    return (<>        {/* <Animated.View style={[styles.box]} /> */}<View style={[styles.box]} /><Button          onPress={() => {            // offset.value = withSpring(Math.random());          }}          title="Move"        /></>    );};

2. With following code

const styles = StyleSheet.create({    box: {        width: '50px',        height: '50px',        backgroundColor: '#000000'    }})export const SignInScreen = (): JSX.Element => {    const offset = useSharedValue(0);    const animatedStyles = useAnimatedStyle(() => {      return {        transform: [{ translateX: offset.value * 255 }],      };    });    return (<><Animated.View style={[styles.box]} />        {/* <View style={[styles.box]} /> */}<Button          onPress={() => {            offset.value = withSpring(Math.random());          }}          title="Move"        /></>    );};

i'm getting errorObject.values requires that input parameter not be null or undefined

Also my configs:

  1. babel
module.exports = (api) => {    api.cache(true);    return {        presets: ['babel-preset-expo'],        plugins: [            ['module-resolver',                {                    alias: {                        assets: './src/assets',                        components: './src/components',                        navigation: './src/navigation',                        screens: './src/screens',                        store: './src/store',                        themes: './src/themes',                    },                },'react-native-reanimated/plugin'            ],        ],        env: {            production: {                plugins: ['react-native-paper/babel'],            },        },    };};
  1. package.json
{"main": "node_modules/expo/AppEntry.js","scripts": {"start": "expo start","android": "expo start --android","ios": "expo start --ios","web": "expo start --web","eject": "expo eject"  },"dependencies": {"@react-native-community/masked-view": "0.1.10","@react-navigation/native": "^5.7.6","@react-navigation/stack": "^5.9.3","expo": "~39.0.2","expo-status-bar": "~1.0.2","react": "16.13.1","react-dom": "16.13.1","react-native": "https://github.com/expo/react-native/archive/sdk-39.0.3.tar.gz","react-native-anchor-point": "^1.0.1","react-native-gesture-handler": "~1.7.0","react-native-paper": "^4.2.0","react-native-reanimated": "^2.0.0-alpha.7","react-native-safe-area-context": "3.1.4","react-native-screens": "~2.10.1","react-native-svg": "12.1.0","react-native-web": "~0.13.12","styled-components": "^5.2.0"  },"devDependencies": {"@types/react": "~16.9.35","@types/react-dom": "~16.9.8","@types/react-native": "~0.63.2","@types/styled-components": "^5.1.4","react-native-web": "~0.13.7","typescript": "~3.9.5"  },"private": true}
  1. tsconfig??
{"compilerOptions": {"baseUrl": "./src","allowSyntheticDefaultImports": true,"jsx": "react-native","lib": ["dom", "esnext"],"moduleResolution": "node","noEmit": true,"skipLibCheck": true,"resolveJsonModule": true,"strict": true,"paths": {"assets": ["./src/assets"],"components": ["./src/components"],"navigation": ["./src/navigation"],"screens": ["./src/screens"],"store": ["./src/store"],"themes": ["./src/themes"],        }    }}

Maybe someone know what can be wrong? Also can add full repo link.

How to update state properly in react hooks

$
0
0

So, The problem is that whenever I press the delete button, it just removes the deletes the last input and the button regardless of the index. I've tried to change the key to key={${index}${name}}`, this won't work that well, because the inputs are changeable (in main code) and that makes thing messed up.How can I make delete properly according to indexes??

function App() {  const [names, setNames] = React.useState(["First", "Second",'third','fourth']);  const onNameDelete = useCallback((index: number) => {    setNames((prev) => {      const name = names[index];      return prev.filter(x => x != name);    });  }, [names]);  return (<div>      {names.map((name, index) => (<Child          key={index}          name={name}          index={index}          onDelete={onNameDelete}        />      ))}</div>  );}interface ChildProps {  name: string;  index: number;  onDelete: (index: number) => void;}export const Child: React.FC<ChildProps> = React.memo(  ({ name, index, onDelete }) => {    return (<div><input          defaultValue={name}        /><button onClick={() => onDelete(index)}>delete</button></div>    );  }

Can not build react-native app after upgrading to 0.63.3

$
0
0

I upgraded to RN 0.63.3 from 0.61.5The problem with typescript during ./gradlew assembleRelease and running from Xcode. What can be the reason ?

Library/Developer/Xcode/DerivedData/ChemoSafe-fnvlvransqahaxdehhyqdidragnt/Build/Products/Release-iphonesimulator/ChemoSafe.appwarning: the transform cache was reset.                 Welcome to React Native!                Learn once, write anywhereerror SyntaxError: /Users/spawn/code/Work/src/screens/App/screens/Assessments/components/DashboardTile/DashboardTileImage/styledComponents.tsx: Unexpected token, expected ";" (71:42)[0m [90m 69 | [39m}[0m[0m [90m 70 | [39m[0m[0m[31m[1m>[22m[39m[90m 71 | [39m[36mconst[39m getProgress [33m=[39m ({progress[33m,[39m [33m...[39mprops})[33m:[39m number [33m=>[39m {[0m[0m [90m    | [39m                                          [31m[1m^[22m[39m[0m[0m [90m 72 | [39m  [36mreturn[39m getStrokeDasharray(props) [33m*[39m ([35m1[39m [33m-[39m progress [33m/[39m [35m100[39m)[0m[0m [90m 73 | [39m}[0m[0m [90m 74 | [39m[0m. Run CLI with --verbose flag for more details.SyntaxError: /Users/spawn/code/Work/src/screens/App/screens/Assessments/components/DashboardTile/DashboardTileImage/styledComponents.tsx: Unexpected token, expected ";" (71:42)[0m [90m 69 | [39m}[0m[0m [90m 70 | [39m[0m[0m[31m[1m>[22m[39m[90m 71 | [39m[36mconst[39m getProgress [33m=[39m ({progress[33m,[39m [33m...[39mprops})[33m:[39m number [33m=>[39m {[0m[0m [90m    | [39m                                          [31m[1m^[22m[39m[0m[0m [90m 72 | [39m  [36mreturn[39m getStrokeDasharray(props) [33m*[39m ([35m1[39m [33m-[39m progress [33m/[39m [35m100[39m)[0m[0m [90m 73 | [39m}[0m[0m [90m 74 | [39m[0m    at Object._raise (/Users/spawn/code/Work/node_modules/@react-native-community/cli/node_modules/@babel/parser/lib/index.js:799:17)    at Object.raiseWithData (/Users/spawn/code/Work/node_modules/@react-native-community/cli/node_modules/@babel/parser/lib/index.js:792:17)    at Object.raise (/Users/spawn/code/Work/node_modules/@react-native-community/cli/node_modules/@babel/parser/lib/index.js:786:17)    at Object.unexpected (/Users/spawn/code/Work/node_modules/@react-native-community/cli/node_modules/@babel/parser/lib/index.js:9068:16)    at Object.semicolon (/Users/spawn/code/Work/node_modules/@react-native-community/cli/node_modules/@babel/parser/lib/index.js:9050:40)    at Object.parseVarStatement (/Users/spawn/code/Work/node_modules/@react-native-community/cli/node_modules/@babel/parser/lib/index.js:12069:10)    at Object.parseStatementContent (/Users/spawn/code/Work/node_modules/@react-native-community/cli/node_modules/@babel/parser/lib/index.js:11660:21)    at Object.parseStatementContent (/Users/spawn/code/Work/node_modules/@react-native-community/cli/node_modules/@babel/parser/lib/index.js:6751:18)    at Object.parseStatement (/Users/spawn/code/Work/node_modules/@react-native-community/cli/node_modules/@babel/parser/lib/index.js:11593:17)    at Object.parseBlockOrModuleBlockBody (/Users/spawn/code/Work/node_modules/@react-native-community/cli/node_modules/@babel/parser/lib/index.js:12175:25)+ [[ false != true ]]+ [[ ! -f /Users/spawn/Library/Developer/Xcode/DerivedData/ChemoSafe-fnvlvransqahaxdehhyqdidragnt/Build/Products/Release-iphonesimulator/ChemoSafe.app/main.jsbundle ]]+ echo 'error: File /Users/spawn/Library/Developer/Xcode/DerivedData/ChemoSafe-fnvlvransqahaxdehhyqdidragnt/Build/Products/Release-iphonesimulator/ChemoSafe.app/main.jsbundle does not exist. This must be a bug with'
// styleComponents.tsx(71:42)const getProgress = ({progress, ...props}): number => {  return getStrokeDasharray(props) * (1 - progress / 100)}

My tsconfing.json:

{"compilerOptions": {"strict": true,"baseUrl": "./","allowSyntheticDefaultImports": true,"esModuleInterop": true,"allowJs": true,"checkJs": false,"declaration": false,"forceConsistentCasingInFileNames": true,"importHelpers": true,"noEmitHelpers": true,"jsx": "react-native","lib": ["dom", "es2015", "esnext"],"skipLibCheck": true,"types": ["jest", "node"],"target": "es2015","module": "esnext","moduleResolution": "node","resolveJsonModule": true,"isolatedModules": true,"noEmit": true,"noEmitOnError": false,"noFallthroughCasesInSwitch": true,"noUnusedLocals": true,"noUnusedParameters": false,"pretty": true,"removeComments": true,"sourceMap": true,"allowUnreachableCode": false,"noImplicitAny": false,"plugins": [      {"name": "typescript-styled-plugin","lint": {"validProperties": ["aspect-ratio","elevation","margin-vertical","margin-horizontal","padding-horizontal","padding-vertical","resize-mode","shadow-color","shadow-opacity","shadow-offset","shadow-radius","text-align-vertical","tint-color","resize-mode"          ]        }      }    ]  },"exclude": ["node_modules"]}

Thanks for the help !

typescript@3.8.3react-native@0.63.3"@babel/core": "^7.12.1","@babel/plugin-transform-runtime": "^7.12.1","@babel/runtime": "^7.12.1",adasdasadasdasadasdas

React Native platform specific import only works with relative paths

$
0
0

I have a platform specific component split into 2 files:

src/components/Foo/Foo.android.tsxsrc/components/Foo/Foo.ios.tsx

I want to import it in a file:

src/screens/Login.tsx

using:

import Foo from "components/Foo/Foo"

Non-platform specific files can be imported that way because I have setup this custom tsconfig for my project:

"paths": {                                /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */"*": ["src/*"],"@components/*": ["src/components/*"],},

However RN bundler does not find the file. I can only import it using relative paths like this:

import Foo from "../../components/Foo/Foo"

I already tried to change my @components paths config to:

"@components/*": ["src/components/*", "src/components/*.android", , "src/components/*.ios"],

without success.

Any idea why the RN bundler is not able to find the import using components import path notation?

How to create unique keys for react Components

$
0
0

So, I've got this component here, which If I don't give unique keys, React renders it incorrectly.I can't give this: key={${name}${index}} as a key because name for each element can be edited so this will cause remount... So, How I make these keys unique? just giving index doesn't work...

{stringArray.map((name, index) => (<Component          key={`${index}_${name}}`}          name={name}          index={index}          onChange={onNameChange}          onDelete={onNameDelete}        />      ))}

Typing out all possible strings to use accessibilityRole?

$
0
0

I'm using accessibilityRole in React Native. Do I have to type out all the possible strings, or is there an import that I can use?

createAccessibilityRole(parent: Element): string {  if(isLink) return 'link'  return 'text'}

Obviously the above doesn't work, so I was wondering if we could import the type class or if we have to code it ourselves?


TypeError: (0 , _taggedTemplateLiteralLoose2.default) is not a function

$
0
0

What is this error? so unhelpful

enter image description here

this is the error im seeing in the simulator

it's nothing to do with that styled component because 1) it was working for ages beforehand 2) it just randomly stopped working 3) if I comment it out or replace it, it points to somewhere else

in the console this is the error stack

enter image description here

as it's completely random I've tried all the usual stuff. restarting the app, resetting the cache, deleting node modules. nothing has worked. cant even google this error and find any results

this is a complete blocker for me. any ideas?

installing d3ML in React without npm

$
0
0

I came across d3ML.js. However, it's not in the npm registry so I can't directly install it. Is there any other to install & use it in a React.js project?

Full screen background image in React Native app iphone 11

$
0
0

I'm currently trying to set a full background image on my login view. I want to be able to fill my Background image on the whole screen for the iphone 11. I've read a bit a bout safeAreaView and SafeAreaViewInset but not sure how I can implement that in my current case.

I've used the following code to do so but noticed that Iphone 11 have like a white bar at the bottom and top of the phone. Is this something that can't be overlapped since it's like the navigation?

const Background = styled.ImageBackground`padding:20px;justify-content:center;width:100%;height:100%;`const styles = StyleSheet.create({        container: {          flex: 1,        },      });

How app currently looks

   return <SafeAreaView style={styles.container}><Background source={require('../../assets/images/background-cover.jpg')}><CoverLogo width={100} height={100} color={Colors.White} /><Introduction loop={false}><TextHeading text={`#test`} /><TextPage text={`Btest2`} /><TextPage text={`Ttest3`} /><TextPage text={`test4 Sign up !`} /></Background></SafeAreaView>

Index.js imports .tsx file after build specifically on windows

$
0
0

I'm trying to build a module I want to modify and use in my project. I cloned the module, installed the dependencies and built it but when I tried to run it I kept getting an error Error: Unable to resulve module './Calendar.tsx' from 'build\index.js'. I then looked at index.js in the build folder and it seems to be be requiring a tsx file which seems wrong.

The module does compile correctly on linux and osx which is even more confusing.

The github issue has both the correct index.js and the version I got:https://github.com/acro5piano/react-native-big-calendar/issues/264

I have 0 expirience using rollup so I don't have any idea what to try next. Is there some windows specific thing I need to add?

axios post request in react native and react app with JSON Stringify and blob

$
0
0

I am making an app in which I am calling an API end point in react native but I am getting this error but in the web app (its done with react) it doesn't show any error, Here is the web app code in react with typescript

 try {        let result: any;        const criteriaWithNoFile = {            content: filterCriteria.content ? filterCriteria.content.trim() : '',            filterLimit: filterCriteria.filterLimit,            sorting: filterCriteria.sorting,            contractionOption: filterCriteria.contractionOption,            contentId: filterCriteria.contentId,            url: filterCriteria.url ? filterCriteria.url.trim() : ''        }        if (localStorage.getItem('currentUserToken')) {            dispatch({                type: LOADER,                payload: true            });            const formData = new FormData();            const jsonFilterCriteria = JSON.stringify(criteriaWithNoFile);            const blobFilterCriteria = new Blob([jsonFilterCriteria], {                type: 'application/json'            });            formData.append("filterData", blobFilterCriteria);            formData.append("filterFile", filterCriteria.selectedFile);            console.log('FormData', formData);            try {                result = await authAxios.post(`${process.env.REACT_APP_BASE_URL}/filter`, formData, {                    headers: {'Content-Type': 'multipart/mixed'                    }                });

and here is the code I am trying in react native

const filterData = {  content: '',  filterLimit: 1000,  sorting: 'NATURAL',  contractionOption: 'LEAVE_CONTRACTION',  contentId: '',  url:'https://stackoverflow.com/questions/37552973/get-the-time-zone-with-react-native',};const data = new FormData();const jsonFilter = JSON.stringify(filterData);const blobFilter = new Blob([jsonFilter], {  type: 'application/json',});data.append('filterData', jsonFilter);data.append('filterFile', selectedFile);await axios  .post('https://capi.beebl.io/filter', data , {    headers: {'Content-Type': 'multipart/mixed',    },  })  .then((res) => console.log(res))  .catch((err) => console.log(err));

Can anyone help me what I am doing wrong....

Viewing all 6214 articles
Browse latest View live


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