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

How to use variables inside require()?

$
0
0

I'm having a problem here and I don't know if it's possible to do this, I'm pulling data as parameters of my route:

onPress={() =>  navigation.navigate('product', {    pathToImage: "../../images/airdots_category.jpg", })

Then, I get them on my other page.

const pathToImage = route.params.pathToImage;

Now, I want to pass the pathToImage into the require():

<Image source={pathToImage} />

But it does not accept, since the path comes correctly, I find it strange because I just put the path inside a variable.

If you have another way of doing it ... please!


Error trying to access the error property of AVPlaybackStatus

$
0
0

I'm new to TypeScript and am trying to work with expo-av for audio playback.

The following code gives me an error: TS2339: Property 'error' does not exist on type 'AVPlaybackStatus'.

const { sound, status } = await Audio.Sound.createAsync(track.mp3);if (status.isLoaded) {  console.info(status.durationMillis);}else {  console.error("track not loaded", status.error);}

I looked at the definition of status and found:

export type AVPlaybackStatus =  | {      isLoaded: false;      androidImplementation?: string;      error?: string; // populated exactly once when an error forces the object to unload    }  | {      isLoaded: true;      androidImplementation?: string;      uri: string;      progressUpdateIntervalMillis: number;      durationMillis?: number;      positionMillis: number;      playableDurationMillis?: number;      seekMillisToleranceBefore?: number;      seekMillisToleranceAfter?: number;      shouldPlay: boolean;      isPlaying: boolean;      isBuffering: boolean;      rate: number;      shouldCorrectPitch: boolean;      volume: number;      isMuted: boolean;      isLooping: boolean;      didJustFinish: boolean; // true exactly once when the track plays to finish    };

I have never seen this construct before but am guessing this is a union or intersection type (?).

How do I access status.error? And what is the typical idiom / construct to work with such types?

Type annotations can only be used in TypeScript files

$
0
0

I have created a new react-native project using:

npx react-native init

But on App.js there is an error here:

const App: () => React$Node = () => {  return (...)}

There is a red underline in "() => React$Node"

And the error is:

Type annotations can only be used in TypeScript files

I know that this can be fixed by just using "const App = () => { ", but I remember that I have created some other projects before that would not have this error when created. I noticed that this started to happen only after I created a project with template typescript. Now every project I create start like this, and I don't think this is the only thing on the code that is different, because I'm finding a lot of odd errors that wouldn't happen before. The project now will only render right if I use typescript, even if I change this line.

My question is: How can I go back to when the project would not require typescript to work??

How to structure React Native navigation for property passing with Typescript

$
0
0

I have a simple React Native app I'm putting together using Typescript and I'm trying to understand how to make the navigation work correctly.

I a list of content sections and when one is selected to open the chosen article in a webview. What I can't grasp is how I am supposed to pass the URL for the webview to load to the view that contains it. Both the navigation list and the web view should fill the screen when they are selected.

As things stand my base component is GuidanceNavigation which contains a Stack.Navigator with a Stack.Screen for the NavigationItems view that lists all the topics and a Stack.Screen for the InstructionView that contains the webview to show the instructions.

As things stand these are all React.Component types and the part I am not clear on is that when I am in the NavigationItems view I select an option and I need the parent view to replace the NavigationItems view with InstructionView, providing the InstructionView with the title and file location for the selected article. As far as I can tell React Navigation does some magic involving passing in some navigation properties, but I can't figure out how that is supposed to work in a Typescript context or how I can pass my typed objects through the Stack Navigator or even whether the Stack Navigator is the correct component to use in this situation. The Typescript-specific documentation talks about passing through navigation properties but doesn't explain how this is related to the navigator object that seems to be available in JavaScript to actually perform navigation.

My code looks like this, it's a while since I have worked with React and my first time using react-native so it's probably neither excellent nor idiomatic:

GuidanceNavigation.tsx:

const Stack = createStackNavigator();export class GuidanceNavigation extends React.Component<{}, {}>  {  render(): JSX.Element {    return (<SafeAreaView style={styles.container} ><NavigationContainer><Stack.Navigator><Stack.Screen name="Choose a topic" component="NavigationItems" /><Stack.Screen name="Instructions" component="InstructionView" /></Stack.Navigator></NavigationContainer></SafeAreaView>    );  };}

NavigationTypes.ts:

export interface IFileLink {    title: string,    file: string}

NavigationItems.tsx:

import { IFileLink } from './NavigationTypes';export class NavigationItems extends React.Component<{}, {}>  {  itemId: number = 0;  readonly items = [    {      section: R.strings.menu_steps,      values: [    { title: R.strings.menu_getting_started, file: "./assets/html/getting-started.html" },     // and so on      ]    },    {      section: R.strings.menu_guidance,      values: [    { title: R.strings.menu_glossary, file: "./assets/html/glossary.html" },        // etc      ]    }  ];  itemList(itemList: Array<IFileLink>): JSX.Element[] {    return itemList.map((it) => this.item(it));  };  navigateToFile(link:IFileLink) {    console.log("Navigation to "+link.title);    // This does not work because navigation comes from ??? somewhere???    navigation.navigate('Instructions', link);  };  item(fileLink:IFileLink): JSX.Element {    return(<Button    key= { this.itemId++ }    title= { fileLink.title }    onPress= {() =>      this.navigateToFile(fileLink)    }      />    );  };  render(): JSX.Element {    return (<ScrollView><Text style={styles.sectionTitle}>{this.items[0].section}</Text>          {this.itemList(this.items[0].values)}<Text style={styles.sectionTitle}>{this.items[1].section}</Text>          {this.itemList(this.items[1].values)}</ScrollView>    )  };}

InstructionView.tsx:

import { IFileLink } from './NavigationTypes';export class InstructionView extends React.Component<IFileLink> {  private fileLink: IFileLink;  constructor(fl: IFileLink) {    super(fl);    this.fileLink = fl;  }  render(): JSX.Element {    return (<WebView          source={{ uri: this.fileLink.file }}          />    );  }}

How can I ensure that I navigate from NavigationItems to InstructionView with the required properties when an item is selected in that list?

HTTPS calls are not working in React Native

$
0
0

I am developing an API call in React Native using Axios but I am not able to hit the backend after release using ./gradlew assembleRelease. in debugging mode the calls are happening, but I don't understand why it is not happening in Build Release. Where's the backend is developed in Node & Express.

Heres the code I am attaching:

App.tsx

 React.useEffect(() => {       getData().then(d => {           setData(d.data)       })    }, [getData])

Services.ts

    const getData = async () => {        axios.defaults.headers.Accept = "application/json";        return axios.get(`https://XX.XXX.XX.XXX/course`)            .then((resultant) => {                console.log(resultant)                return resultant.data;            })            .catch((error) => {                console.error(error);            });}export {getData}

Proper Typescript type for a reused screen in react-navigation v5

$
0
0

For most of the cases, I follow a simple pattern to type any screen under react-navigation v5:

// Params definitiontype RouteParamsList = {    Screen1: {        paramA: number    }    Screen2: undefined}// Screen1type Props = StackScreenProps<RouteParamsList, 'Screen1'>export const Screen1: React.FC<Props> = ...

That works perfectly.

I can't figure out the proper types for a case when I'd want to reuse the Screen1 for different navigators though:

// Params definitiontype RouteParamsListShop = {    Screen1: {        paramA: number    }    Screen2: undefined    Screen3: undefined}type RouteParamsListFeatures = {    Screen1: {        paramA: number    }    Screen4: undefined}// Screen1type Props = StackScreenProps<RouteParamsListShop, 'Screen1'> | StackScreenProps<RouteParamsListFeatures, 'Screen1'> // Tried thisexport const Screen1: React.FC<Props> = ...

As I commented, I tried to have a union type covering both cases. It allows to get the parameters from the route properly, but navigate method breaks:

This expression is not callable. Each member of the union type '/* Route info here */' has signatures, but none of those signatures are compatible with each other.ts(2349)

Is there a way to properly type it, or I rather have to change the structure of my navigation to make the screen only part of one route? (alternatively, create 2 wrappers for different navigation).

what is the best way to send an js object to firebase?

$
0
0

I am using functional component of react native fully. I've been using it for about 1 week now but I'm still trying to get used to typescript.So I have written a functional component of a TextInput called StyledTextInput, I have no idea if I am in the right direction, I use React.useState<string>(""); in the parent to update the text, however I noticed there is a slight delay when updating the text.I have a simple signup form, which will only be used 1 time:

  1. phone number
  2. gender
  3. occupation
  4. favoriteColor
  5. favoriteSong
const [num, setNum]       = React.useState<number>(0);const [gender, setGender] = React.useState<string>("");const [job, setJob]       = React.useState<string>("");const [color, setColor]   = React.useState<string>("");const [song, setSong]     = React.useState<string>("");

So base on firebase documentation I see sending request is using Javascript Object right? https://rnfirebase.io/app/usage so to send an object I can imagine it look something like this?

function sendObject(){    const sendThis = { num: num, gender: gender, job: job, color: color, song: song };    firebase.database().ref(url).push(sendThis).}

The problem is there is some delay in set of useState. I am not looking for external library, I know there are external library like https://github.com/react-hook-form/react-hook-form but how do they store edit and send the object?
Is there a more elegant way to make sure the sendThis object is up to date? I am wondering is it possible to pass the object to the StyledTextInput and update the value accordingly? Please guide me how.

ViewStyle is not assignable to type StyleProp

$
0
0

i am new to react-native and typescript so might be missing or making some silly mistake that's giving this error mentioned below. I'm creating a component which uses some other library where the "InnerComponent" lives and i am just importing it. I need to pass value from OuterComponent prop which is named as "myCustomContainer" to the InnerComponent prop which is named as "containerStyle" so i specified the same type of prop(StyleProp) as it's expecting in the InnerComponent but getting the following error.

Type 'import("c:/myApp/node_modules/@types/react-native/index").StyleProp<import("c:/myApp/node_modules/@types/react-native/index").ViewStyle>'    is not assignable to type 'import("c:/myApp/node_modules/@types/react-native/index").StyleProp<import("c:/myApp/node_modules/@types/react-native/index").ViewStyle>'.  Type 'ViewStyle' is not assignable to type 'StyleProp<ViewStyle>'.    Type 'import("c:/myApp/node_modules/@types/react-native/index").ViewStyle' is not assignable to type 'import("c:/myApp/node_modules/@types/react-native/index").ViewStyle'.      Types of property 'backgroundColor' are incompatible.        Type 'string | typeof import("c:/myApp/node_modules/@types/react-native/index").OpaqueColorValue | undefined' is not assignable to type 'string | typeof import("c:/myApp/node_modules/@types/react-native/index").OpaqueColorValue | undefined'.          Type 'unique symbol' is not assignable to type 'string | unique symbol | undefined'.ts(2322)             InnerComponent.d.ts(12, 5): The expected type comes from property 'containerStyle' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes<InnerComponent> & Pick<Readonly<Props> & Readonly<{ children?: ReactNode; }>, "myCustomText" | ... 12 more ... | "someOtherContainerStyle"> & Partial<...> & Partial<...>'

Here is the code for the component i created and typed definition file(d.ts) of the imported component.

My Component

import React from "react";import { View, StyleProp, ViewStyle } from "react-native";import { NavigationInjectedProps, withNavigation } from "react-navigation";import { InnerComponent } from "ComponentsLibrary";import { myStyles as styles } from "../styles";interface IProps {  myText?: string;  myCustomContainer?: StyleProp<ViewStyle>}type Props = IProps & NavigationInjectedProps;export const MyOuterComponent: React.FC<Props> = (props: Props) => {  const {    myText,    myCustomContainerStyle  } = props;  return (<View><InnerComponent          customText={myText}          containerStyle={myCustomContainerStyle}          onChangeText={(e) => console.log(e.target.value)}        />   </View>  );};

InnerComponent.d.ts file for the component i am using

import { Component } from "react";import { StyleProp, ViewStyle } from "react-native";/** * Component Props */declare type Props = {    containerStyle?: StyleProp<ViewStyle>;    someOtherContainerStyle?: StyleProp<ViewStyle>;    customText?: string;    onChangeText: (customText: string) => void;};/** * Component State */declare type State = {    isTextMode: boolean;    customText: string;};export declare class InnerComponent extends Component<Props, State> {    static defaultProps: {        onChange: undefined;    };    constructor(props: Props);    someFunction: () => void;    componentDidUpdate(prevProps: Props): void;    render(): JSX.Element;    private onCancel;}export default InnerComponent;

Enviroment variable at React Native does not working using TypeScript

$
0
0

I added the react-native-dotenv library and followed the guide using TypeScript.

I created a .env file

MARVEL_API = <url>MARVEL_PUBLIC_KEY = <public-key>MARVEL_PRIVATE_KEY = <private-key>

I added this options at babel.config.js file at the presets

'module:react-native-dotenv',    {      moduleName: '@env',      path: '.env',      whitelist: ['MARVEL_API', 'MARVEL_PUBLIC_KEY', 'MARVEL_PRIVATE_KEY'],      safe: false,      allowUndefined: true,    },

I created a types folder with the end.d.ts file and I declared the @env as

declare module '@env' {  export const MARVEL_API: string;  export const MARVEL_PUBLIC_KEY: string;  export const MARVEL_PRIVATE_KEY: string;}

Whe I saved the files, launched this error:

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

I saw to write yarn start --reset-cache but it did not work.

Cannot read property of undefined in react navigation native with typescript

$
0
0

I'm building a react native app and I'm having trouble passing props to another screen using react-navigation/native.

Navigation set up

export type RootStackParamList = {  Home: HomeProps,  LoginDemo: undefined,  Login: undefined};const Stack = createStackNavigator<RootStackParamList>();const store = configureStore();export const Navigation: React.FC = () => {  return (<Provider store={store}><NavigationContainer><Stack.Navigator><Stack.Screen name="LoginDemo" component={LoginDemo} /><Stack.Screen name="Home" component={Home}/><Stack.Screen name="Login" component={LoginScreen} /></Stack.Navigator></NavigationContainer></Provider>  );};

Code that does the screen switching

React.useEffect(() => {    if (patrolUnits.completed) {      if (patrolUnits.error !== null)        showAlert("error", patrolUnits.error.toString());      else        navigation.replace('Home', {patrolUnitId: patrolUnits.data[0].id});    }  }, [patrolUnits.completed]);

The screen that I am switching to

export const Home: React.FC<RouteProp<RootStackParamList, "Home">> = routeProps => {    const props = routeProps.params;    const { patrolUnitId } = props;    return (<View><Text>{patrolUnitId.toString()}</Text></View>)};

And the props that should be passed

export type HomeProps = {    patrolUnitId: number;}

Can anyone tell me what I'm doing wrong. I've been trying to figure this out for hours. I've tried googling but almost everything that's recommended for me is for regular react, not react native.

React Native with typescript unable to resolve modules

$
0
0

This is embarrassing, but I don't know what else to do. I wanted to port my little React Native project to TypeScript, so I created an empty React Native project with TypeScript template, tweaked tsconfig.json to use custom paths such as @app and I tried to run it. It didn't. And this was yesterday, I did some googling, but those who had the same issue suggested to clean the packager, remove node_modules and reinstall packages all over, for example, this one, so I did, and it didn't work.

These are my steps for reinstalling react-native-cli (at first I thought that the problem is with outdated package, it wasn't):

  • npm uninstall -g react-native-cli
  • yarn global add @react-native-community/cli

Those below I followed already that many times, that I don't remember the exact number:

  • npx react-native init MyApp --template react-native-template-typescript
  • yarn add redux redux-logger redux-thunk react-redux
  • yarn add --dev @types/react @types/react-redux @types/redux-logger

And then making changes to tsconfig.json, so it looks likes this ( my changes marked with ->):

{"compilerOptions": {    /* Basic Options */"target": "esnext",                       /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */"module": "esnext",                       /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */"lib": ["dom", "esnext"],                 /* Specify library files to be included in the compilation. */"allowJs": true,                          /* Allow javascript files to be compiled. */"jsx": "react-native",                    /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */"noEmit": true,                           /* Do not emit outputs. */"incremental": true,                      /* Enable incremental compilation */"isolatedModules": true,                  /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */    /* Strict Type-Checking Options */"strict": true,                           /* Enable all strict type-checking options. */    /* Module Resolution Options */"moduleResolution": "node",               /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */->  "baseUrl": "./src",                       /* Base directory to resolve non-absolute module names. */->  "paths": {                                /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */->    "@app/*": ["./*"]->  },"allowSyntheticDefaultImports": true,     /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */"esModuleInterop": true                   /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */      },"exclude": ["node_modules", "babel.config.js", "metro.config.js", "jest.config.js"  ]}

My project structure looks like this:

MyApp├── ios├── android├── src│├── index.tsx│├── constants││└── app.json│├── support   ││└── store.tsx   │└── reducers   │└── index.tsx├── tsconfig.json├── package.json├── index.js └── [ the rest ]

And when I'm trying to import {initStore} from '@app/support/store' in MyApp/src/index.tsx the Metro gives me the following:

Loading dependency graph, done.error: bundling failed: Error: Unable to resolve module `@app/support/store` from `src/index.tsx`: @app/support/store could not be found within the project.

Then I tried cleaning with following commands, but it also didn't do any good:

  • watchman watch-del-all && rm -rf $TMPDIR/react-* && rm -rf node_modules/ && npm cache verify && npm install && npm start -- --reset-cache

But, what interesting, after that I tweaked tsconfig.json, Atom doesn't complain about paths like @app/support/store, it even provides autocompletion, it recognizes @app/support/ as directory and @app/support/store as a script, so I assume tsconfig.json is not the problem.

Difference b/w React Typescript , React JavaScript and React Native?

$
0
0

I have confusion about React JavaScript , React Typescript and React Native.

I just have idea that we use React Native for mobile applications and and React (Javascript,Typescript) for web applications.

Can someone exactly draw the difference between them ?Which parent library/framework those use ?

Like Angular can we make components,services in them(React JavaScript , React Typescript and React Native).

And when we simply say React what does it mean (Native , Typescript or Javascript) ?

JavaScript: Shorthand to toggle a non-boolean value

$
0
0

Is there a better shorthand to toggle foo?

type Foo = 'ON' | 'OFF';let foo: Foo = 'ON';const toggleFoo = () => {  foo = foo === 'ON' ? 'OFF' : foo;};toggleFoo();

Cannot update a child component on his parent

$
0
0

Well, I'm pretty new with React Native and I'm trying to update a child component on his Parent, the thing is that I'm giving this error (Warning: Cannot update a component from inside the function body of a different component.) and I don't know what to do.

https://imgur.com/a/1LhMsfY -> The father component.

const CallList: React.FC<NavigationProps> = (props) => {  const [absences, setAbsences] = useState<Array<Array<{    id: number,    checked: boolean  }>>>([]);  // const [absences, setAbsences] = useState([{'id': 0, 'checked': false},{'id': 1, 'checked': false}]);  const { setOptions } = useNavigation();  const {aula} = props.route.params;  const [students, setStudents] = useState<Array<StudentProps>>([]);  const [loading, setLoading] = useState<boolean>(false);  const {signOut, docente, anoSemMat} = useAuth();

https://imgur.com/a/FMe98UQ -> That's the place where I call the Child Component (StudentsList)

if (loading || absences.length == 0 || students.length == 0) return <Loading/>;  else {    return (<><ScrollView style={styles.scrollView} contentContainerStyle={{ flexGrow: 1, marginTop: 30}}><SafeAreaView><TouchableWithoutFeedback onPress={Keyboard.dismiss}><KeyboardAvoidingView behavior = "position"><View style={styles.container}>                        {students.map((student, idx) => {                            return <StudentsList                                      key={student.NRO_ALUNO}                                      student={student}                                      value={absences[idx]}                                      onChange={(classes, nroAluno) => setAbsences(changeAbsenceStudent(classes, nroAluno))}                                      // onChange={(classes, nroAluno) => setAbsences(classes)}                                    />                        })}<Button onPress={() => console.log(absences)} title="click"/></View></KeyboardAvoidingView></TouchableWithoutFeedback></SafeAreaView></ScrollView></>    );  }

https://imgur.com/a/mZFKLiB -> The Child Component

interface Students {    student: StudentsListProps;    onChange: (classes: Array<{      id: number,      checked: boolean    }>, pos: number) => void;    value: Array<{      id: number,      checked: boolean    }>}interface StudentsState {    isVisible: boolean,    checkAll: boolean,    classes: Array<{        id: number,        checked: boolean    }>,    student: StudentsListProps}export default class StudentsList extends React.Component<Students, StudentsState> {  constructor(props : Students) {    super(props)    const { student, value } = this.props;    this.state = {      isVisible: false,      checkAll: false,      classes: value,      student: student    }  }

All I need is to get the value from StudentsList on CallList but I don't know the best way to do that so I made this "onChange" in StudentsList.

Creating a cross-sdk wrapper for Firebase (Firestore, Cloud Storage, and more)

$
0
0

I'm currently trying to find an abstraction that can allow me to run Firebase products (mainly Firestore, Storage, and Analytics) regardless of the platform (React Native, React, Node.js). I have looked at the REST API but would like to use the SDKs for all the features that they offer.

// webimport firebase from 'firebase';type WebFirestore = ReturnType<typeof firebase.firestore>;// cloudimport * as admin from 'firebase-admin';type CloudFirestore = ReturnType<typeof admin.firestore>;// nativeimport { FirebaseFirestoreTypes } from '@react-native-firebase/firestore';type NativeFirestore = FirebaseFirestoreTypes.Module;const API = (firestore: WebFirestore | CloudFirestore | NativeFirestore) => {  firestore    .collection('foo')    .doc('foo')    .get()    .then((resp) => true);}

I'm trying to create a TypeScript type that can enable me to do the same (at least that's what I think). The API, on the outset, is kept consistent across platforms for these products but my guess is that the return types are different. By that I mean, I can run this function on all platforms as long as the firestore object belongs to the SDK on that platform.

I was thinking of creating a class that takes a flag ('web', 'cloud', 'native') and then also take the firestore object in the constructor. I tried running the code below but TypeScript says the following:

(property) Promise<T>.then: (<TResult1 = FirebaseFirestore.DocumentSnapshot<FirebaseFirestore.DocumentData>, TResult2 = never>(onfulfilled?: (value: FirebaseFirestore.DocumentSnapshot<FirebaseFirestore.DocumentData>) => TResult1 | PromiseLike<...>, onrejected?: (reason: any) => TResult2 | PromiseLike<...>) => Promise<...>) | (<TResult1 = firebase.firestore.DocumentSnapshot<...>, TResult2 = never>(onfulfilled?: (value: firebase.firestore.DocumentSnapshot<...>) => TResult1 | PromiseLike<...>, onrejected?: (reason: any) => TResult2 | PromiseLike<...>) => Promise<...>) | (<TResult1 = FirebaseFirestoreTypes.DocumentSnapshot<...>, TResult2 = never>(onfulfilled?: (value: FirebaseFirestoreTypes.DocumentSnapshot<...>) => TResult1 | PromiseLike<...>, onrejected?: (reason: any) => TResult2 | PromiseLike<...>) => Promise<...>)Attaches callbacks for the resolution and/or rejection of the Promise.@param onfulfilled — The callback to execute when the Promise is resolved.@param onrejected — The callback to execute when the Promise is rejected.@returns — A Promise for the completion of which ever callback is executed.This expression is not callable.  Each member of the union type '(<TResult1 = DocumentSnapshot<DocumentData>, TResult2 = never>(onfulfilled?: (value: DocumentSnapshot<DocumentData>) => TResult1 | PromiseLike<...>, onrejected?: (reason: any) => TResult2 | PromiseLike<...>) => Promise<...>) | (<TResult1 = DocumentSnapshot<...>, TResult2 = never>(onfulfilled?: (value: DocumentSnapsh...' has signatures, but none of those signatures are compatible with each other.ts(2349)

I'm rather new to TypeScript and was wondering if there is a way to make this work. All the types individually work but their union doesn't work. Is there a better way to think about this layer of abstraction in TypeScript? I intend to host this on the Github package registry and all the products to have access to the internal API as functions that are currently - firestore, cloud storage, cloud functions, some REST API calls.


How to pass props to an imported component in styled-components

$
0
0

a challenge has arisen here, I'm using React Native and I need to pass props to RectButton, does anyone know how?

Because it is not a standard React Native feature, it is imported from react-native-gesture-handler, so I don't have access to it through styled-components, I would like something 'like this':

export const CheckBoxInput = styled(RectButton)<CheckBoxInputProps>`  border: 1px solid ${h4_app_color};  width: 20px;  height: 20px;  border-radius: 20px;  ${(props) =>    props.filled      ? css`          background-color: ${h4_app_color};        `      : css`          background-color: white;        `}`;

My props are like this:

interface CheckBoxInputProps {  filled?: boolean;}

Styled Components and TypeScript: No overload matches this call

$
0
0

I'm new to Style Components and I'm trying to build a weather app using React Native. I would normally use CSS modules but it seems that this isn't an option for mobile development.

Here's the code:

import ThemeModel from 'models/ThemeModel'import React, { PureComponent } from 'react'import styled from 'styled-components/native'interface HomeScreenComponentInterface {  theme?: ThemeModel  getWeatherData: () => void;  isLoading: boolean | null;}class HomeScreenComponent extends PureComponent<HomeScreenComponentInterface> {  componentDidMount() {    const { getWeatherData } = this.props    getWeatherData()  }  render() {    const Container = styled.View`    padding: 20px 0;  `    const HeaderText = styled.Text`    color: ${(props: HomeScreenComponentInterface) => props.theme && props.theme.colors.lightBlue};    font-size: ${(props: HomeScreenComponentInterface) => props.theme && props.theme.fontSizes.xLarge};    font-weight: 500;  `    return (<Container><HeaderText>Weather App</HeaderText></Container>    )  }}

And here is a screen shot off the error:

overload error

Here's the Theme.tsx

import React, { FC, ReactNode } from 'react'import { ThemeProvider } from 'styled-components'const theme = {  colors: {    powderWhite: '#FFFDF9',    persianGreen: '#06B49A',    lightBlue: '#AFDBD2',    onyx: '#36313D',  },  fonts: ['sans-serif', 'Roboto'],  fontSizes: {    small: '12px',    medium: '16px',    large: '24px',    xLarge: '32px',  },}interface ThemeProps {  children: ReactNode}const Theme: FC<ThemeProps> = ({ children }) => (<ThemeProvider theme={ theme }>{children}</ThemeProvider>)export default Theme

I believe I only need to pass the theme props to this component, but I can't figure out how to do that..

Any help would be must appreciated.

react unknown error "index.js:63 Uncaught TypeError: Cannot read property 'nodeName' of null"

$
0
0

Using React and Bootstrap to create a dialog (deleted everything unnecessary, but the error persists):

import React, {    Component,} from 'react';import {    Modal,} from 'react-bootstrap';class MyDialog_MultiSelect extends Component<any, any> {    constructor(        props:      any    ) {        super(props);    }    render() {        return (<Modal                animation       = {false}                aria-labelledby = "contained-modal-title-vcenter"                backdrop        = "static"                centered                dialogClassName =  "ms-modal"                keyboard        = {true}                show            = {true}                size            = "lg"><Modal.Header                     closeButton></Modal.Header><Modal.Body></Modal.Body></Modal>        );    }}export default MyDialog_MultiSelect;

When opening a dialog in the browser console (Chrome), an error is displayed:

index.js:63 Uncaught TypeError: Cannot read property 'nodeName' of null    at _e (index.js:63)    at MutationObserver.<anonymous> (index.js:63)

The dialog works, but this error is annoying.

What is this error and how can it be fixed?

How to show dynamic options , rows and column in react fixed data table

$
0
0

I am using the react fixed data table.

<Table                rowHeight={50}                rowsCount={rows.length}                width={800}                height={300}                headerHeight={50}><Column                    header={<Cell>Name</Cell>}                    cell={({ rowIndex}) => (<Cell>                            {rows[rowIndex].userId}</Cell>                        ) }                    width={200}                /><Column                    header={<Cell>Description</Cell>}                    cell={({ rowIndex }) => (<Cell >                            {rows[rowIndex].description}</Cell>                        ) }                    width={200}                />

currently it is taking the header name as name(static) and for cell value i need to give the column name.

I have written to show to dynamic header and row value based on json response.

    renderTableHeader() {    if(this.state.data !== 'undefined'&& this.state.data !==null && this.state.data.length >0)    {    let header = Object.keys(this.state.data[0])    return header.map((key, index) => {       return <th key={index}>{key.toUpperCase()}</th>    })    } } renderTableData() {    return this.state.data.map((student, index) => {       let col = Object.keys(student)       return (<tr key={student.id}>             {col.map((val, index) => {                return <td key={index}>{student[col[index]]}</td>             })}</tr>       )    }) }

but don't know how to give here.

<Column                header={<Cell>Name</Cell>}                cell={({ rowIndex}) => (<Cell>                        {rows[rowIndex].userId}</Cell>                    ) }                width={200}            />

Also i want to give the filter options based on my json response, not hardcoded.

   class Record extends React.Component {constructor(props){    super(props);    this.state = {        data: [],        selectTableOptions : [],    }    this.handleTableChange = this.handleTableChange.bind(this);    //All these fields i want come as json response    this.options = [        {            columnField: "Name",            type:"text"        },        {            columnField: "description",            type:"text"        },        {            columnField: "Status",            type:"selection"        },        {            columnText: "Email @",            columnField: "Email",            type:"text"        }    ];    this.customAutoComplete = new CustomAutoComplete(this.state.data,this.options);}

Jest tests fail after adding Typescript to a React Native project

$
0
0

So, I just added TypeScript to an existing React Native project (first commit dates from Feb 2016), and I'm getting the follwing errors when running unit tests (using Jest):

  1. This is the one that is showing in most files, I'd say 30 out of 38 failed testsenter image description here

  2. This one already has a mock in the mock filesenter image description here

  3. This one shows up on two filesenter image description here

  4. This one shows up on just one fileenter image description here

This only happens when adding ts, I've only modified three files from the project to use it as I have to go slowly because it's a huge project.

I've tried out with different setups for jest.config.js but nothing changes:

jest.config.js

const { defaults: tsjPreset } = require('ts-jest/presets');module.exports = {    ...tsjPreset,    globals: {'ts-jest': {            babelConfig: true,        }    },    moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],    modulePaths: ['<rootDir>'],    preset: 'react-native',    transform: {        ...tsjPreset.transform,'^.+\\.(js)$': '<rootDir>/node_modules/babel-jest','^.+\\.(ts|tsx)?$': '<rootDir>/node_modules/ts-jest/preprocessor.js',    },    transformIgnorePatterns: ['node_modules/(?!(texts/@debitoor/react-native-sunstone/))/'],};

tsconfig.json

{"compilerOptions": {"allowJs": true,"allowSyntheticDefaultImports": true,"baseUrl": "./app","esModuleInterop": true,"isolatedModules": true,"jsx": "react","lib": ["es2017"],"moduleResolution": "node","noEmit": true,"paths": {"common": ["./common"]        },"skipLibCheck": true,"strict": false,"target": "esnext"    },"exclude": ["node_modules","babel.config.js","metro.config.js","jest.config.js"    ]}

I tried removing the exclude elements at same thing happens. Not sure what else I'm missing.

I also tried using ts-jest but nothing changed either.

This is the tsconfig.jest.json file:

{"extends": "./tsconfig","compilerOptions": {"jsx": "react","module": "commonjs"    }}

I've searched around and in most articles/sites they always talk about starting fresh, but I've already got everything else setup and can't really change much without taking too much time.

Any ideas would be great!

Viewing all 6288 articles
Browse latest View live


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