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

getTheme() native base Type

$
0
0

I'm using a custom Native Base style theme as described in this link.

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

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)}>

Inside getTheme(), on material, I get this TypeScript error:

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"

How do I get rid of this?

inside the native-base-themes folder, there's a material.js file that 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,    },  },};

How to animate expanding / collapsing a text preview in react native with Animated.View

$
0
0

I'm creating a text component that I want to be 2 lines by default, and if the user taps on it, it will expand to the full length, and if the user taps on it again, it will collapse back to 2 lines.

So far I have something like this in my return function:

<TouchableWithoutFeedback    onPress={() => {      toggleExpansion();    }}><Animated.View style={[{ height: animationHeight }]}><Text      style={styles.textStyle}      onLayout={event => setHeight(event.nativeEvent.layout.height)}      numberOfLines={numberOfLines}>      {longText}</Text></Animated.View></TouchableWithoutFeedback>

My state variables and toggleExpansion function look like this:

const [expanded, setExpanded] = useState(false);const [height, setHeight] = useState(0);const [numberOfLines, setNumberOfLines] = useState();const toggleExpansion = () => {  setExpanded(!expanded);  if (expanded) {    setNumberOfLines(undefined);  } else {    setNumberOfLines(2);  }};

So far this works to expand and collapse but I'm not sure how to set the Animated.timing function to animate it. I tried something like this:

const animationHeight = useRef(new Animated.Value(0)).current;useEffect(() => {  Animated.timing(animationHeight, {    duration: 1000,    toValue: height,    easing: Easing.linear  }).start();}, [height]);

but it didn't quite work. It doesn't display the text at all, and when I try initializing the new Animated.Value to a bigger number than the 2 line height (like 50), the height always gets truncated to 16 no matter how many times I expand and collapse. What's the best way to animate expanding and collapsing the text?

RefferenceError: Can't find variable React

$
0
0

I'm not entirely sure why I am getting this error, as react is present in node_modules and imported in referenced file

enter image description here

Referred App.js file is this one

"use strict";var __importDefault = (this && this.__importDefault) || function (mod) {    return (mod && mod.__esModule) ? mod : { "default": mod };};Object.defineProperty(exports, "__esModule", { value: true });const react_1 = __importDefault(require("react"));const unstated_1 = require("unstated");const layouts_1 = __importDefault(require("./layouts"));const App = () => (<unstated_1.Provider><layouts_1.default /></unstated_1.Provider>);exports.default = App;

This is output from TypeScript ^. Non transpiled version is as follows

import React from 'react'import { Provider as StateProvider } from 'unstated'import AppRoot from './layouts'const App = () => (<StateProvider><AppRoot /></StateProvider>)export default App

My project structure looks like this

packages/  native-app/    node_modules/    ios    index.js    src/      App.tsx    dist/      native-app/        src/          App.js      server/  server/

I feel like this might be related to nesting inside dist folder? My main react native index.js imports App like this

import { AppRegistry } from 'react-native'import App from './dist/native-app/src/App'AppRegistry.registerComponent('MyApp', () => App)

Note: This looks like monorepo, but I am not using anything like yarn workspaces or lerna, packages are installed inside each folder i.e. native-app and server with some common devDependencies like typescript, tslint and prettier installed in root folder where packages are located.

Project uses following tsconfig

{"compilerOptions": {"target": "es2017","module": "commonjs","lib": ["es2017"],"removeComments": true,"allowSyntheticDefaultImports": true,"esModuleInterop": true,"skipLibCheck": true,"strict": true,"noImplicitAny": true,"strictNullChecks": true,"strictFunctionTypes": true,"noImplicitThis": true,"alwaysStrict": true,"noUnusedLocals": true,"noUnusedParameters": true,"noImplicitReturns": true,"noFallthroughCasesInSwitch": true  },"exclude": ["scripts","packages/native-app/dist","packages/server/functions/dist"  ]}

And package json for native-app

{"name": "skimitar-app","version": "1.0.0","description": "Skimitar app","private": true,"dependencies": {"asq-react-native-device": "1.2.2","asq-react-native-facebook-log-in": "1.1.0","asq-react-native-google-sign-in": "1.2.0","asq-react-native-sensors": "1.1.0","react": "16.4.2","react-native": "0.56.0","react-native-firebase": "4.3.8","react-native-svg": "6.5.2","unstated": "2.1.1"  },"devDependencies": {"@types/react": "16.4.13","@types/react-native": "0.56.17"  }}

TypeError: seamless immutable _1.default is not a function - React native jest unit testing (Typescript)

$
0
0

I am trying jest unit testing for typescript based react native project.Now I am stuck on one issue when do npm test. Error mentioned below

● Test suite failed to run

TypeError: seamless_immutable_1.default is not a function  34 |   35 | > 36 | export const INITIAL_STATE: ImmutableAppReducerState = Immutable({     |                                                                 ^  37 |   activeTab: 0,  38 |   showTab: false,  39 |   tabName: "",

My actual code was follows

import Immutable from "seamless-immutable";

export interface AppReducerState {  activeTab?: number | undefined;  showTab?: boolean | undefined;  tabName?: string | undefined;  isDrawerOpen: boolean;  retryAction: AnyAction[];}/* ------------- Initial State ------------- */type ImmutableAppReducerState = Immutable.Immutable<AppReducerState>export const INITIAL_STATE: ImmutableAppReducerState = Immutable({  activeTab: 0,  showTab: false,  tabName: "",  isDrawerOpen: false,  retryAction: [],});

React Navigation Typescript namespace not found

$
0
0

When I'm trying to create any navigator( tab/ stack/ drawer) I get this typescript error: Cannot find namespace 'Tab' even when it's defined in the file itself.What's the problem and what's the solution?I've used the expo typescript template to begin.

Problem

The "injectBabelPlugin" helper has been deprecated as of v2.0. You can use customize-cra plugins in replacement

$
0
0

I am trying to customize my imports using babel. I am following this link:

https://medium.com/@leonardobrunolima/react-tips-working-with-relative-path-using-create-react-app-fe55c5f97a21

This is my config-overrides.js

const { injectBabelPlugin } = require('react-app-rewired');const rootImportConfig = ["root-import",    {        rootPathPrefix: "~",        rootPathSuffix: "src"    }];module.exports = config => injectBabelPlugin(rootImportConfig, config);

Package.json:

"scripts": {"start": "react-app-rewired start","build": "react-app-rewired build",

Currently, this gives me an error that:The "injectBabelPlugin" helper has been deprecated as of v2.0. You can use customize-cra plugins in replacement

Hence, I installed

nom install customize-cra react-app-rewired --dev

and changed 'react-app-rewired' to 'customize-cra' in my js file as suggested here:https://github.com/arackaf/customize-cra#available-plugins

However, that still doesn't work since the injectBabelPlugin is also depreciated. What the function should I use here then? I tried the config files from here but it doesn't work from me either. It's src-functionality is also different.

https://github.com/timarney/react-app-rewired/issues/348

How can I fix my config file and imports? Instead of

import { ResultAlert } from '../../components/alerts/ResultAlert';

I want to do something like this:

import {ResultAlert} from '~/components';

Unknown Option error from Babel in React-Native app

$
0
0

I ma building a react-native app with typescript in order to learn react native. Once I run the app with expo start and try to run on emulator I get this error:

index.js: [BABEL] ......../index.js: Unknown option: .name. Check out https://babeljs.io/docs/en/babel-core/#options for more information about options

Actually I didn't have this error before. I tried to install react-native-dotenv package and while doing it installed metro-react-native-babel-preset too, which I am not sure whether was already installed or not.

My package.json is as follows:

{"name": "mobile-app","version": "0.0.1","private": true,"scripts": {"android": "react-native run-android","ios": "react-native run-ios","start": "react-native start","test": "jest","lint": "eslint . --ext .js,.jsx,.ts,.tsx" },"dependencies": {"@react-native-community/async-storage": "^1.12.0","@react-native-community/google-signin": "^4.0.3","@types/axios": "^0.14.0","axios": "^0.20.0","expo": "^38.0.10","react": "16.13.1","react-native": "0.62.2" },"devDependencies": {"@babel/core": "^7.8.4","@babel/runtime": "^7.8.4","@react-native-community/eslint-config": "^1.1.0","@types/jest": "^25.2.3","@types/react-native": "^0.63.2","@types/react-native-dotenv": "^0.2.0","@types/react-test-renderer": "^16.9.2","@typescript-eslint/eslint-plugin": "^2.27.0","@typescript-eslint/parser": "^2.27.0","babel-jest": "^25.1.0","eslint": "^6.5.1","jest": "^25.1.0","react-native-clean-project": "^3.4.0","react-native-dotenv": "^2.4.1","react-test-renderer": "16.13.1","typescript": "^3.8.3" },"jest": {"preset": "react-native","moduleFileExtensions": ["ts","tsx","js","jsx","json","node"   ] }}

babel.config.js :

module.exports = {  presets: ['module:metro-react-native-babel-preset', 'module:react-native-dotenv'],};

index.js

/** * @format */import { AppRegistry } from 'react-native';import App from './App';import { name as appName } from './app.json';AppRegistry.registerComponent('main', () => App);

How to use AWS Amplify in React Native with Typescript Project?

$
0
0

I'm trying to add Amplify Authentication in my react native project which uses typescript.There is a package given in amplify documentation 'aws-amplify-react-native' which is used as a middleware to authenticate our application.But this package is only supported in projects which are based on javascript.For Typescript it shows an error like

Could not find a declaration file for module 'aws-amplify-react-native'.Try `npm install @types/aws-amplify-react-native` if it exists or add a new declaration (.d.ts) file containing `declare module 'aws-amplify-react-native';`

There is no package available like '@types/aws-amplify-react-native'

So anyone can help me out of this?


invalid date format TypeScript

$
0
0

I am passing in time values departureTime such as '12:00' here. Then I try to convert it into a date and perform a subtraction. However, the result of timeOfDeparture and then time till departure is invalid. How can I fix this and make everything in a uniform type?

    const timeNow = new Date();    console.log('TIME NOW', timeNow)    const timeOfDeparture = new Date(departureTime);    console.log('TIME of Departure', timeOfDeparture)    const timeTillDeparture = Math.floor((timeOfDeparture.valueOf() - timeNow.valueOf()) / 60000);    console.log('TIME TILL DEP', timeOfDeparture)

Example console logs:

TIME NOW Tue Oct 06 2020 15:47:35 GMT+0200 (Central European Summer Time)TIME of Departure Invalid DateTripTimes.tsx:17 TIME TILL DEP NaN

Error: react-redux module can't resolve module redux

$
0
0

I'm using React Native with the typescript template: npx react-native init someapp --template react-native-template-typescript

Whenever I try to: import {Provider} from 'react-redux'; in index.js or App.tsx

I get the follow error:error: Error: Unable to resolve module ../../../../redux from node_modules\react-redux\lib\connect\mapDispatchToProps.js:

Note: no errors are occurred when I import redux in the project to create the redux store.

Here's my package.json:

{"name": "someapp","version": "0.0.1","private": true,"scripts": {"android": "react-native run-android","ios": "react-native run-ios","start": "react-native start","test": "jest","lint": "eslint . --ext .js,.jsx,.ts,.tsx"  },"dependencies": {"@react-native-community/masked-view": "^0.1.10","@react-navigation/material-bottom-tabs": "^5.2.16","@react-navigation/native": "^5.7.3","@react-navigation/stack": "^5.9.0","@reduxjs/toolkit": "^1.4.0","@types/react-native-webrtc": "^1.75.1","@types/react-redux": "^7.1.9","@types/redux": "3.6.31","axios": "^0.20.0","react": "16.13.1","react-native": "0.63.2","react-native-config": "^1.3.3","react-native-elements": "^2.2.1","react-native-gesture-handler": "^1.7.0","react-native-linear-gradient": "^2.5.6","react-native-paper": "^4.0.1","react-native-reanimated": "^1.13.0","react-native-safe-area-context": "^3.1.6","react-native-screens": "^2.10.1","react-native-svg": "^12.1.0","react-native-vector-icons": "^7.0.0","react-native-webrtc": "^1.84.0","react-redux": "^7.2.1","redux": "^4.0.5"  },"devDependencies": {"@babel/core": "^7.8.4","@babel/runtime": "^7.8.4","@react-native-community/eslint-config": "^1.1.0","@types/jest": "^25.2.3","@types/react-native": "^0.63.2","@types/react-test-renderer": "^16.9.2","@typescript-eslint/eslint-plugin": "^2.27.0","@typescript-eslint/parser": "^2.27.0","babel-jest": "^25.1.0","babel-plugin-module-resolver": "3.2.0","eslint": "^6.5.1","eslint-import-resolver-babel-module": "5.1.0","eslint-plugin-import": "2.18.2","jest": "^25.1.0","metro-react-native-babel-preset": "^0.59.0","prettier": "^2.0.4","react-native-svg-transformer": "^0.14.3","react-test-renderer": "16.13.1","redux-devtools": "^3.7.0","typescript": "^3.8.3"  },"jest": {"preset": "react-native","moduleFileExtensions": ["ts","tsx","js","jsx","json","node"    ]  }}

Things I tried:

  • Removing node_modules -> delete yarn.lock -> yarn cache clean -> yarn -> cd android -> ./gradlew clean -> cd .. -> yarn android

  • Adding/Removing/Trying one without the other: "@types/react-redux": "^7.1.9", "@types/redux": "3.6.31",

  • Made sure that "moduleResolution": "node" is in the compilerOptions in tsconfig.json

  • Trying different versions of redux and react-redux

react-redux can't find module redux

$
0
0

I'm using React Native with the typescript template: npx react-native init someapp --template react-native-template-typescript

Whenever I try to: import {Provider} from 'react-redux'; in index.js or App.tsx

I get the following error:
Error: Unable to resolve module ../../../../redux from node_modules\react-redux\lib\connect\mapDispatchToProps.js:

Note: no errors are occurred when I import redux in the project to create the redux store.

Here's my package.json:

{"name": "someapp","version": "0.0.1","private": true,"scripts": {"android": "react-native run-android","ios": "react-native run-ios","start": "react-native start","test": "jest","lint": "eslint . --ext .js,.jsx,.ts,.tsx"  },"dependencies": {"@react-native-community/masked-view": "^0.1.10","@react-navigation/material-bottom-tabs": "^5.2.16","@react-navigation/native": "^5.7.3","@react-navigation/stack": "^5.9.0","@reduxjs/toolkit": "^1.4.0","@types/react-native-webrtc": "^1.75.1","@types/react-redux": "^7.1.9","@types/redux": "3.6.31","axios": "^0.20.0","react": "16.13.1","react-native": "0.63.2","react-native-config": "^1.3.3","react-native-elements": "^2.2.1","react-native-gesture-handler": "^1.7.0","react-native-linear-gradient": "^2.5.6","react-native-paper": "^4.0.1","react-native-reanimated": "^1.13.0","react-native-safe-area-context": "^3.1.6","react-native-screens": "^2.10.1","react-native-svg": "^12.1.0","react-native-vector-icons": "^7.0.0","react-native-webrtc": "^1.84.0","react-redux": "^7.2.1","redux": "^4.0.5"  },"devDependencies": {"@babel/core": "^7.8.4","@babel/runtime": "^7.8.4","@react-native-community/eslint-config": "^1.1.0","@types/jest": "^25.2.3","@types/react-native": "^0.63.2","@types/react-test-renderer": "^16.9.2","@typescript-eslint/eslint-plugin": "^2.27.0","@typescript-eslint/parser": "^2.27.0","babel-jest": "^25.1.0","babel-plugin-module-resolver": "3.2.0","eslint": "^6.5.1","eslint-import-resolver-babel-module": "5.1.0","eslint-plugin-import": "2.18.2","jest": "^25.1.0","metro-react-native-babel-preset": "^0.59.0","prettier": "^2.0.4","react-native-svg-transformer": "^0.14.3","react-test-renderer": "16.13.1","redux-devtools": "^3.7.0","typescript": "^3.8.3"  },"jest": {"preset": "react-native","moduleFileExtensions": ["ts","tsx","js","jsx","json","node"    ]  }}

Things I tried:

  • Removing node_modules -> delete yarn.lock -> yarn cache clean -> yarn -> cd android -> ./gradlew clean -> cd .. -> yarn android

  • Adding/Removing/Trying one without the other: "@types/react-redux": "^7.1.9", "@types/redux": "3.6.31",

  • Made sure that "moduleResolution": "node" is in the compilerOptions in tsconfig.json

  • Trying different versions of redux and react-redux

Rollup is not adding react-native components to bundle imports

$
0
0

I try to build a react-native/-web library to share components between two projects,but rollup is not recognising the react-native components when they are used in a component and response with this error:

(!) Unused external importsView,Text,TouchableOpacity,ActivityIndicator,TextInput,Picker,FlatList,StatusBar imported from external module 'react-native' but never useddefault imported from external module 'react-native-easy-content-loader' but never usedSvg,G,Path,default,Polygon,Polyline,Rect,Circle,Defs,Mask,Use imported from external module 'react-native-svg' but never usedTextInputMask imported from external module 'react-native-masked-text' but never used

It also means that it is not importing them in the bundle files:

import { StyleSheet, Platform, UIManager, LayoutAnimation, Dimensions, PixelRatio, Animated, PanResponder, Image } from 'react-native';

This is my rollup config:

import alias from '@rollup/plugin-alias';import jsx from 'acorn-jsx';import path from 'path';import typescript from 'rollup-plugin-typescript2';import pkg from './package.json';export default {  input: 'src/index.ts',  output: [    {      file: pkg.main,      format: 'cjs',      sourcemap: true,    },    {      file: pkg.module,      format: 'esm',      sourcemap: true,    },  ],  external: [    ...Object.keys(pkg.dependencies || {}),    ...Object.keys(pkg.peerDependencies || {}),  ],  acornInjectPlugins: [jsx()],  plugins: [    alias({      entries: {        components: path.resolve(__dirname, './src/components'),        context: path.resolve(__dirname, './src/context'),        gql: path.resolve(__dirname, './src/gql'),        types: path.resolve(__dirname, './src/types'),        utils: path.resolve(__dirname, './src/utils'),      },    }),    typescript({      typescript: require('ttypescript'),      tsconfigDefaults: {        compilerOptions: {          plugins: [            {transform: 'typescript-transform-paths'},            {transform: 'typescript-transform-paths', afterDeclarations: true},          ],        },      },    }),  ],};

and my tsconfig.json:

{"compilerOptions": {"allowSyntheticDefaultImports": true,"baseUrl": ".","declaration": true,"declarationDir": "dist","jsx": "react-native","module": "esnext","moduleResolution": "node","sourceMap": true,"target": "es5","paths": {"components/*": ["src/components/*"      ],"context/*": ["src/context/*"      ],"gql/*": ["src/gql/*"      ],"types/*": ["src/types/*"      ],"utils/*": ["src/utils/*"      ],    },  },"include": ["src/**/*"  ],"exclude": ["node_modules","../../node_modules","dist","src/**/*.stories.*","src/**/*.test.*"  ]}

I'm not sure if I do something wrong in my config or if this is a bug with the rollup tree shaking.Hope someone can help.Thanks.

Why is XCode Compiling very slow after adding typescript?

$
0
0

I finally switched to typescript for my react native project this week. I find it beautiful and awesome. However, when I go to compile my project in Xcode, it is taking forever!(that is a metaphorical forever, approximately 30 minutes which is 6x longer than usual).

Am I missing something? Is there a different typescript compile command?

I am running:

XCODE: Version 12.0.1 (12A7300)deploying ios: 10 (in both the project and podfile)RN: 0.63typescript: 4.0.3

place text next to thumbnail instead of center

$
0
0

Currently, my username text appears in the center of the view. I want to change it such that it appears on the exact right of the thumbnail. If I remove the alignItems: 'center', from the item, it disturbs the whole style. How else can I fix this?

import { StyleSheet, Alert } from 'react-native';import { View, Text, Button, Thumbnail } from 'native-base';import Icon from 'react-native-vector-icons/FontAwesome';import { moderateScale } from 'react-native-size-matters';import { TouchableOpacity } from 'react-native-gesture-handler'; return (<View style={styles.item}><TouchableOpacity><Thumbnail          style={styles.thumbnail}          source={{            uri:'https://cdn4.iconfinder.com/data/icons/avatars-xmas-giveaway/128/afro_woman_female_person-512.png',          }}        /></TouchableOpacity><View style={styles.nameContainer}><Text style={styles.userName}>USER NAME</Text></View><Button        rounded        style={styles.deleteButton}><Icon name="trash-o" size={moderateScale(20)} color="black" /></Button></View>  );};const styles = StyleSheet.create({  item: {    backgroundColor: 'pink',    borderRadius: moderateScale(20),    padding: moderateScale(20),    marginVertical: moderateScale(8),    marginHorizontal: 16,    height: moderateScale(70),    justifyContent: 'space-between',    flexDirection: 'row',    alignItems: 'center',  },  thumbnail: {    height: 70,    width: 70,    position: 'relative',  },  nameContainer: {    //flex: 1,    // alignItems: 'center',    // textAlign: 'center',  },  userName: {    paddingRight: moderateScale(55),    paddingLeft: moderateScale(20),    //textAlign: 'center',    color: 'white',    fontWeight: '900'  },  deleteButton: {    backgroundColor: '#31C283',    width: moderateScale(45),    justifyContent: 'center',  },  horizontalLine: {    marginTop: moderateScale(30),    width: '87%',    height: moderateScale(1),    backgroundColor: 'grey',    alignSelf: 'center',  },});

I tried creating a snack expo but I am unable to use native base in it.

enter image description here

How to fix a TypeScript false positive warning for "No overload matches this call."?

$
0
0

I have a React Native component that will render an Animated.View with an animated style for Android, otherwise it renders a View without this style.

My code is:

interface ButtonProps {  containerStyle?: StyleProp<ViewStyle>;}const Button: React.FC<ButtonProps> = ({ containerStyle }) => {  let ContainerView: typeof View | typeof Animated.View = View;  let viewShadow: AnimatedViewStyle | null = null;  if (Platform.OS === 'android') {    ContainerView = Animated.View;    // pressedAnim is an `Animated.Value` that I omitted from the code so it is simpler to read    viewShadow = {      elevation: pressedAnim.interpolate({        inputRange: [0, 1],        outputRange: [2, 8]      })    };  }  return {<ContainerView style={[styles.container, containerStyle, viewShadow]} />  }}const styles = StyleSheet.create({  container: { /* some style */ }});

The TypeScript warning No overload matches this call. is cause by the viewShadow. If I remove it from the style prop, the warning is dismissed. If I use only an Animated.View and keep the viewShadow, the warning is dismissed too.

So, the problem here is that the Animated.View and viewShadow are only used together, so this is a false-positive warning.

How can I fix this? Is there another way to write this code so TypeScript won't warn that something is wrong?


align placeHolder text in vertical center

$
0
0

The placeholder and typed text in my input field seems to be a bit lower than the center. Is there any way to vertically align it in the center? I have already tried alignItems, justifyContent and textAlign but none of them seem to do the trick.

export const Input: FunctionComponent = () => {  return (<Item rounded style={styles.inputItem}><Icon name='search' size={moderateScale(18)} color="#bdbdbd" style={styles.icon}/><Input        style={styles.inputField}        placeholder="Search Text"        placeholderTextColor="grey"      /></Item>  );};const styles = StyleSheet.create({  inputItem: {    width: moderateScale(330),    backgroundColor: 'white',    borderBottomColor: 'grey',    borderRadius: moderateScale(10),    height: verticalScale(40),    paddingLeft: moderateScale(10),  },  icon: {    paddingRight: moderateScale(10),  },  inputField: {    fontSize: moderateScale(15),    borderBottomColor: 'transparent',    marginTop: 3,  },});

underline the clicked text element

$
0
0

I have a list of text elements that I want to underline when clicked. If I add the text decoration to the tabText then obviously it is applied to all items. How can I make sure that the when I click on another tab, the underline from the previous tab gets removed?

Is there any way I can add or remove items from the style element upon clicking on an item?

//onPress={() => {}}>const tabs = [  {    id: 1,    text: 'Alle List',  },  {    id: 2,    text: 'Second',  },];export const Tab: React.FunctionComponent = () => {  return (<View style={styles.tabView}>      {tabs.map((item: any) => (<View><Text style={styles.tabText}>{item.text}</Text></View>      ))}</View>  );};const styles = StyleSheet.create({  tabView: {    paddingTop: moderateScale(15),    paddingLeft: moderateScale(20),    paddingRight: moderateScale(20),    flexDirection: 'row',    justifyContent: 'space-between',  },  tabText: {    color: 'white',    paddingBottom: moderateScale(10),    //textDecorationLine: 'underline'  },});

Codesandbox (with tabText items as an array too):

https://snack.expo.io/@nhammad/shallow-watermelon

Typescript error JSX element type 'View' is not a constructor function for JSX elements

$
0
0

The program itself runs fine, but Typescript is underlining a lot of items in red in my return function for my components. Specifically anything coming out of my react-native import.

Anything like View, Button, and the like are throwing these "errors". I say errors in quotes because the app runs without any problems at all. Typescript within my IDE (VS Code) is the only thing complaining. It throws these errors if I choose (through the bottom right status bar selector) JavaScript React or TypeScript React. Here is an example:

Text Problem

Here is the important bits of my package.json

"scripts": {"start": "expo start","android": "expo start --android","ios": "expo start --ios","web": "expo start --web","eject": "expo eject"  },"dependencies": {"@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-screens": "~2.10.1","react-native-web": "~0.13.12","react-native-gesture-handler": "~1.7.0","react-native-reanimated": "~1.13.0","react-native-safe-area-context": "3.1.4","@react-native-community/masked-view": "0.1.10"  },"devDependencies": {"react-native-web": "~0.13.7","@types/react": "*","@types/react-dom": "*","@types/react-native": "*","typescript": "~3.9.5"  },

And here is what a file looks like that is throwing these errors:

import { StatusBar } from "expo-status-bar";import React, { useState } from "react";import { StyleSheet, Text, View, TextInput, Button } from "react-native";const SummaryScreen = ({ navigation }) => {    const accountDetailsPage = () => {        navigation.navigate("Account Details");    };    const contactDetailsPage = () => {        navigation.navigate("Contact Details");    };    return (<View style={styles.container}><Text>HERE IS A BUNCH OF TEXT</Text><Button title="Account Details" onPress={accountDetailsPage} /><Button title="Contact Details" onPress={contactDetailsPage} /></View>    );};const styles = StyleSheet.create({    container: {        flex: 1,        backgroundColor: "#fff",        flexDirection: "column",        alignItems: "center",        justifyContent: "center",    },});export default SummaryScreen;

I think it's important to note I do NOT get these errors on components created from @react-navigation such as <Navigator> and <Stack.Screen ...

Here is my tsconfig as well:

{"compilerOptions": {"allowSyntheticDefaultImports": true,"jsx": "react-native","lib": ["dom", "esnext"],"moduleResolution": "node","noEmit": true,"skipLibCheck": true,"resolveJsonModule": true,"strict": true    }}

Somewhat related, something in VS Code is complaining it can't find the module for useState but that also works fine when running, with no errors

React Native still runs with incorrectly defined types (TypeScript)

$
0
0

I am trying to convert React Native project to TypeScript-based project.So far, I converted .jsx files to .tsx files, and when I run yarn tsc, it throws tons of error.However, my npx react-native start&& npx react-native run-android still just runs without any complaining. (I tried cleaning cache)

I intentionally defined one of the variables to incorrect type and code still just runs fine. What I am doing wrong? Why does my project still work?

My tsconfig.json looks like this

{"compilerOptions": {"allowJs": true,"allowSyntheticDefaultImports": true,"esModuleInterop": true,"isolatedModules": true,"jsx": "react","lib": ["es6"],"moduleResolution": "node","noEmit": true,"noEmitOnError": true,"noImplicitAny": false,"strict": true,"target": "esnext"  },"exclude": ["node_modules","babel.config.js","metro.config.js","jest.config.js"  ]}

React-native-reanimated not working in web

$
0
0

Currently i`m copied example from this posthttps://github.com/software-mansion/react-native-reanimated/issues/537When trying in web Reanimated not working and RN Animated working well.

There is no errors or warnings. Just animation not starting.Versions:

"react-native": "https://github.com/expo/react-native/archive/sdk-39.0.2.tar.gz","react-native-web": "~0.13.12","react-native-reanimated": "~1.13.0","expo": "~39.0.2",

Maybe someone know how to solve this issue?

Viewing all 6214 articles
Browse latest View live


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