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

The value on the Context Provider doesn't change

$
0
0

So, I'm learning about React Context and try to implement it by creating an auth state for my React Native app. I tried following this Ben Awad's repo. This is what I've got so far:

// AuthContext.tsxexport const AuthContext = createContext<{  user: null | string;  login: () => void;}>({  user: null,  login: () => {},});export const AuthProvider = ({ children }: Props) => {  const [user, setUser] = useState<null | string>(null);  const { user: contextUser } = useContext(AuthContext);  return (<AuthContext.Provider      value={{        user,        login: () => {          setUser("My Name");          console.log("Auth Provider pressed");          console.log("user (state) " + user);          console.log("contextUser (context) " + contextUser);        },      }}>      {children}</AuthContext.Provider>  );};// Navigation.tsxexport const Navigation = ({}: Props) => {  const { user } = useContext(AuthContext);  return (<AuthProvider>        {user ? <HomeScreen /> : <Button />}</AuthProvider>// Button.tsxexport const Button = ({}: Props) => {  const { login } = useContext(AuthContext);  return (<View><Touchable          onPress={login}><Text style={styles.container}>Submit</Text></Touchable></View>  )

The AuthProvider has 2 values. user which is obtained from the useState(). And, login which calls the setUser to change the user on the useState() and thus should change the user on the first Provider value.

The onPress on Button will call login() from the AuthProvider. The login() on the AuthProvider will trigger setUser to change the user on the useState() value from null to "My Name". Until this part, it works as expected.

But, even though the button successfully changes the user value on the useState(). It doesn't change the user (changed to contextUser for "debugging" purpose) on the Context, no mater how many times I click the button, the contextUser will always be null.

Tl;dr: user value on AuthProvider doesn't change after the button is pressed. But, user on useState changes.

So, what happened? What did I do wrong? Anyone has any idea how to fix this? I've stuck with this issue for the last few hours and googled more about this. My code is similar to theirs (I compared mine with other people's code that also uses context & auth), but somehow this code doesn't work.

Anyway, on Navigation, it should also automatically re-renders (to be HomeScreen) after the user value on Context is changed to non-null. I still haven't tested if it'll work (well, the user value never changes). Anyone could also review it to see if it could also run as expected?


Could not be found within the project

$
0
0

Im struggling here.

I could not install a NPM registry properly from Github so I decided to install the files manually.

I created a folder called /libs and I copied across the files and changed all the import statments

ie from:

import {ParticipationType} from '@registryName/lib';

to:

import {ParticipationType} from 'views/libs/types';

I then deleted the package from package.json, ran yarn install and then proceeded to run my project with npx react-native run-android and I get the following error:

error: bundling failed: Error: Unable to resolve module `views/libs/types` from `views/pages/Dashboard/DashboardView.tsx`: views/libs/types could not be found within the project.

Im really confused as the ParticipationType file is present in the views/libs/types folder but its not picking up on it in the console.

Things i've tried so far:

Clear watchman watches: watchman watch-del-all

and

Delete node_modules: rm -rf node_modules and run yarn install

and

Reset Metro's cache: yarn start --reset-cache

All help welcome

Change text input color for hashtags react native mobx

$
0
0

I want to dynamically change the color of words in a textInput element where a hashtag comes up. Similar to a lot of apps. Here is what i have so far:

@observable descriptionString: any = '';@observable formattedText: any = ;handleCheckTextChange = (inputText:any) => {    const words = inputText.split('');    console.log(words);    const formattedText:any = [];    words.forEach((word:any, index:any) => {      const isLastWord = index === words.length - 1;      if (!word.startsWith('@')) {        return isLastWord ? formattedText.push(word) : formattedText.push(word, '');      }      const mention = (<Text key={word + index} style={{color: 'red'}}>          {word}</Text>      );      isLastWord ? formattedText.push(mention) : formattedText.push(mention, '');    });    this.formattedText = formattedText;  }

The text input:

<TextInput            maxLength={descriptionMaxLength}            multiline={true}            placeholder='Type description here'            style={styles.descriptionInput}            returnKeyType='next'            blurOnSubmit={true}            onChangeText={(text) => this.handleCheckTextChange(text)}><Text>{this.formattedText}</Text></TextInput>

I got this from another stack overflow question, but it doesn't seem to work with my code. Getting a mobx error saying "Dynamic observable objects cannot be frozen." I am using mobx for state handling and the error is a mobx error so i am think that this may be an issue with setting and changing that formattedText observable. Any help is appreciated!

How to change all colors inside the Card

$
0
0

At the layout when the status is Fechado I need to change the Card and all data inside to a gray color.

Remembering that the Title, Description, Separator, Classification, MinimumValue and Profitability are the components that I created.

How can I do something easier than passing some disable properties to each component and changing the color? And how would I do that with the stars as they are .png images.

Layout:

enter image description here

Code of funds page.

return (<>      {funds.sort((fundA, fundB) => fundA.name.localeCompare(fundB.name)).map((fund) => (<CardContainer key={fund.id} status={fund.status}><CardHeader><View><Title title={fund.name} style={{ fontSize: 14, flexWrap: "wrap" }} /><Description description={fund.type} /></View><Status><StatusText>Novo</StatusText></Status></CardHeader><Separator /><CardFooter><Classification rating={fund.rating} /><MinimumValue price={fund.minimumValue} /><Profitability percentage={fund.profitability} /></CardFooter></CardContainer>      ))}</>  );

Styles of funds page

import styled from 'styled-components/native';export const CardContainer = styled.View`  width: 320px;  padding: 5px 17px;  min-height: 185px;  background-color: #fff;  border-radius: 10px;  margin: auto;  margin-top: 20px;  border: 1px solid #dae0e3;`;export const CardHeader = styled.View`  justify-content: space-between;  margin-top: 5px;  align-items: center;  flex-direction: row;`;export const Status = styled.View`  align-items: center;  justify-content: center;  width: 56px;  height: 20px;  background-color: #36c4d6;  border-radius: 10px;`;export const StatusText = styled.Text`  font-family: 'Montserrat-Medium';  color: #fff;  font-size: 10px;`;export const CardFooter = styled.View`  margin-top: 10px;  flex-direction: column;  justify-content: center;  margin-bottom: 5px;`;

useRef.current is undefined in a React Native functional component

$
0
0

I'm trying to focus a text input field once the user clicks a button. The code looks as follows:

const refName = React.useRef();const changeFocus = () => {    refName.current.focus();}

with the text input having an attribute ref defined as refName.This gives me an error (undefined is not an object (evaluating 'refName.current.focus')), and when I rewrite the changeFocus function as console.log(refName) this is what I get:

Object {"current": undefined,}

I'm not sure how else I'm supposed to define the reference or how else to approach this problem.Thanks

React Native (or React) listen to the style changes for the dark mode in separate ts modules

$
0
0

Goal: Implement dark mode in react native application.A little introduction to the system:File structure:

  • Profile.ts
  • ProfileCss.ts
  • constants.ts

In my application in order to separate styles from components, I moved them into .ts files and exported as modules.Example of StyleCss.ts:

import {StyleSheet} from 'react-native';import {Window, FixedCSS, hsize, wsize} from '../../entities/constants';export default StyleSheet.create({    loading: {        backgroundColor: FixedCSS.Colors.MainBackgroundColor,    }    ...});

All style-related constant values stored in constants.ts such as Colors, LineHeights, and etc. Also constants.ts contains a class called FixedCSS which has static properties:

export class FixedCSS {    static isDark = true;    static Colors = {        // Main Colors        RootColor: FixedCSS.isDark ? '#FF6666' : '#FF6666',        MainBackgroundColor: FixedCSS.isDark ? '#050505' : '#FFFFFF',        ...    }    ...}

isDark property of FixedCSS is supposed to be changed with the help of Switch component in Profile.ts

<Switch    value={darkMode}    onValueChange={value => {        this.setState({darkMode: value});    }}/>

The problem: How can I change isDark property in FixedCSS class so that it will affect the appearance of components. The most problematic aspect is that StyleCSS.ts files do not reflect to the change of isDark property in FixedCSS class, as they are exported only once when js bundle gets created.

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

$
0
0

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

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

it is my code

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

or

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

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

Button to reload the screen when the WiFi is off

$
0
0

I have a screen that I verify if the WiFi is connected. If the WiFi is off I show in the screen a message and a button Try Again but I would like to click in this button and refresh the screen.

WiFiError Component

import React, { useCallback } from 'react';import { useNavigation } from '@react-navigation/native';import Title from '../Title';import Description from '../Description';import { View, Button, Text } from './styles';interface IWifiErrorProps {  text: string;  navigateTo: string;}const WifiError: React.FC<IWifiErrorProps> = ({ text, navigateTo  }) => {  const navigation = useNavigation();  const handleRefreshTheScreen = useCallback((navigateTo) => {    navigation.navigate(navigateTo);  }, [navigation]);  return (<View><Title title='Ocorreu um erro.' /><Description description={`Não foi possível se conectar ao banco de ${text}.`} /><Button onPress={() => handleRefreshTheScreen(navigateTo)}><Text>TENTAR NOVAMENTE</Text></Button></View>  );}export default WifiError;

When I turn off the WiFi at Dashboard and I navigate to "Ações" appear this as a warning "Possible Unhandled Promise Rejection".


The property favorited does not exists at the object

$
0
0

I am calling the third-party API and the data does not have the favorited property, then I added the property favorited at the interface StocksProps:

Interface StocksProps

interface StocksProps {  id: number;  name: string;  ticker: string;  minimumValue: number;  profitability: number;  favorited: boolean;}

But at the time when I call the API I use the setStocks remembering that this API call is inside the useEffect hook.The API data comes

"success":true,"data":[ {   ... }, {   ... },],"error": null

API get

api.get('stocks').then((response) => {  const stocksDataOrdered =    response.data.data.sort((stockA: StocksProps, stockB: StocksProps) =>      stockA.name.localeCompare(stockB.name));  setStocks(stocksDataOrdered);  setLoading(false);});

And I'm trying to make the heart empty, full after I click on the heart, but when I give a console.log () in the action that has the id, it doesn't come with any properties called favorited.

const handleStockAsFavorite = useCallback((id: number) => {   const stockToChangeTheFavoriteValue = stocks.find(element => element.id === id);   console.log(stockToChangeTheFavoriteValue);   setFavoriteStock(false)}, [stocks]);
<FavoriteButton onPress={() => handleStockAsFavorite(stock.id)}><FavoriteImage source={favoriteStock ? favoritedImg : unfavoriteImg} /></FavoriteButton>

The log comes{"id": 3, "minimumValue": 400.2, "name": "Banco do Brasil Seguridade", "profitability": 27.05, "ticker": "BBSE3"}

Adding type for useRef on ScrollView react-native

$
0
0

Looking to create a ref to a ScrollView component like so: const ref = useRef<ScrollView>(null); (or something to this effect) essentially I need access to the flashScrollIndicators method like this:

<ScrollView  ref={ref}  onContentSizeChange={() => ref?.current?.flashScrollIndicators()}>  {children}</ScrollView>

The code does work in my app however typescripts definitions for ScrollView doesn't seem to include flashScrollIndicators?I'm getting Property 'flashScrollIndicators' does not exist on type 'ScrollView'.ts(2339) looking through the types I can see SectionList and Flatlist so unsure if this is an bug with the definitions or just me not using it properly.

How do i rerender my screen after deletion from list?

$
0
0

Hello I've been looking through several threads on stackoverflow but I haven't been able to solve my problem. I have an app where you can save movies to a watchlist. On this specific screen I want to display a users watchlist and give them the ability to delete it from the list. Currently the function is indeed deleting the movie from the list and removing it from firebase but i can't get my screen to rerender to visually represent the deletion.

This is the code right now:

export default function MovieWatchlistTab(props: any) {  let { movies } = props;  let movieWatchlist: any[] = [];  const [watchlistSnapshot, setWatchlistSnapshot] = useState();  const user: firebase.User = auth().currentUser;  const { email } = user;  const watchlistRef = firestore().collection("Watchlist");  useEffect(() => {    getWatchlistSnapshot();  }, []);  const getWatchlistSnapshot = async () => {    setWatchlistSnapshot(await watchlistRef.where("userId", "==", email).get());  };  const convertDataToArray = () => {    const convertedMovieList = [];    for (let movie in movies) {      let newMovie = {        backdrop: movies[movie].backdrop,        overview: movies[movie].overview,        release: movies[movie].release,        title: movies[movie].title,      };      convertedMovieList.push(newMovie);    }    movieWatchlist = convertedMovieList;  };  const renderMovieList = () => {    convertDataToArray();    return movieWatchlist.map((m) => {      const handleOnPressDelete = () => {        const documentRef = watchlistRef.doc(watchlistSnapshot.docs[0].id);        const FieldValue = firestore.FieldValue;        documentRef.set(          {            movies: {              [m.title]: FieldValue.delete(),            },          },          { merge: true }        );        movieWatchlist.splice(          movieWatchlist.indexOf(m),          movieWatchlist.indexOf(m) + 1        );        console.log("movieWatchlist", movieWatchlist);      };      const swipeButtons = [        {          text: "Delete",          color: "white",          backgroundColor: "#b9042c",          onPress: handleOnPressDelete,        },      ];      return (<Swipeout right={swipeButtons} backgroundColor={"#18181b"}><View key={m.title} style={{ marginTop: 10, flexDirection: "row" }}><Image              style={{ height: 113, width: 150 }}              source={{                uri: m.backdrop,              }}            /><View><Text                style={{                  flex: 1,                  color: "white",                  marginLeft: 10,                  fontSize: 17,                }}>                {m.title}</Text><Text style={{ flex: 1, color: "white", marginLeft: 10 }}>                Release: {m.release}</Text></View></View></Swipeout>      );    });  };  return (<View      style={{        flex: 1,        justifyContent: "center",        alignItems: "center",        backgroundColor: "#18181b",      }}><ScrollView        style={{ flex: 1 }}        contentContainerStyle={{          width: Dimensions.get("window").width,        }}>        {renderMovieList()}</ScrollView></View>  );}

I've been trying to play around with useStates and I think the answer is in that direction but I just can't seem to get it to work anyway. Any help would be appreciated!

Default Values with Interface in Arrow Function (TypeScript, React)

$
0
0

This question is specific to arrow functions. Is it possible to include the default values alongside an interface in the function parameters, and without resorting to Object.assign()?

interface Props {  someBoolean?: boolean;  anotherBoolean?: boolean;  children: any;}const DefaultValues = {  someBoolean: false,  anotherBoolean: false,}export const StackOverflow: React.FC<Props> = (_props: Props) => {  const props = Object.assign({}, _props, DefaultValues);  return <React.Fragment>{props.children}</React.Fragment>;};

Typescript access object key dynamically

$
0
0

I have Theme.ts file like below

export default {  COLORS: {    DEFAULT: '#172B4D',    PRIMARY: '#5E72E4',    SECONDARY: '#F7FAFC',  }};

In my button component I import above theme file like this --> import argonTheme from "../constants/Theme";

In my button component I want to get access to that color dynamically like this

 const { small, shadowless, children, color, style, fontSize } = props; const colorStyle = color && argonTheme.COLORS[color.toUpperCase()];

This line gives me typescript error --> const colorStyle = color && argonTheme.COLORS[color.toUpperCase()];

This is the error I'm getting

Element implicitly has an 'any' type because expression of type 'any' can't be used to index type '{ DEFAULT: string; PRIMARY: string; SECONDARY: string ...

How can I write this line in typescript ?

const colorStyle = color && argonTheme.COLORS[color.toUpperCase()];

React Natice Expo: How can I change 「BottomTab.Screen」name type alias to Japanese?

$
0
0

BackgroundI try first time React Native Expo with typescript.so, I have no idea to use BottomTab.Screen.

Q. I would like to change 「name="TabOne"」to Japanese is 「ホーム」.

// navigation/BottomTabNavigator.tsxconst BottomTab = createBottomTabNavigator<BottomTabParamList>();export default function BottomTabNavigator() {  const colorScheme = useColorScheme();  return (<BottomTab.Navigator      initialRouteName="TabOne"      tabBarOptions={{ activeTintColor: Colors[colorScheme].tint }}><BottomTab.Screen        name="TabOne" // ホーム        component={TabOneNavigator}        options={{          tabBarIcon: ({ color }) => <TabBarIcon name="home" color={color} />,        }}      /><BottomTab.Screen        name="TabTwo"// タスク        component={TabTwoNavigator}        options={{          tabBarIcon: ({ color }) => <TabBarIcon name="task" color={color} />,        }}      /></BottomTab.Navigator>  );}
// types.txexport type BottomTabParamList = {  TabOne: undefined;  TabTwo: undefined;};

※ memoThis project is React Native Expo with TypeSript.

Const variable as type - Typescript

$
0
0

During learning Typescript I faced problem when I used constant variable with the value of action which I use to reducer (created to prevent typo - I have read somewhere it is good practice).

const INPUT_CHANGE: string = "INPUT_CHANGE";const INPUT_BLUR: string = "INPUT_BLUR";

I also have created type to define reducer action:

type InputReducerAction =  | { type: INPUT_CHANGE; value: string; isValid: boolean }  | { type: INPUT_BLUR };

And here is my reducer:

const inputReducer = (state: InputReducerState, action: InputReducerAction) => {  switch (action.type) {    case INPUT_CHANGE:      return {        ...state,        value: action.value,        isValid: action.isValid,      };    case INPUT_BLUR:      return {        ...state,        touched: true,      };    default:      return state;  }};

When I have everythink like above INPUT_CHANGE and INPUT_BLUR in InputReducerAction are marked as error:

'INPUT_CHANGE' refers to a value, but is being used as a type here. Did you mean 'typeof INPUT_CHANGE'?ts(2749)

'INPUT_BLUR' refers to a value, but is being used as a type here. Did you mean 'typeof INPUT_BLUR'?ts(2749)

Problem disappear when I use double quotes for this constants, like so

type InputReducerAction =  | { type: "INPUT_CHANGE"; value: string; isValid: boolean }  | { type: "INPUT_BLUR" };

But my const variables are useless right now. What I have done wrong or missed?

During writing this question I got idea to use enum:

enum INPUT_ACTION {  INPUT_CHANGE = "INPUT_CHANGE",  INPUT_BLUR = "INPUT_BLUR"}type InputReducerAction =  | { type: INPUT_ACTION.INPUT_CHANGE; value: string; isValid: boolean }  | { type: INPUT_ACTION.INPUT_BLUR };const inputReducer = (state: InputReducerState, action: InputReducerAction) => {  switch (action.type) {    case INPUT_ACTION.INPUT_CHANGE:      return {        ...state,        value: action.value,        isValid: action.isValid,      };    case INPUT_ACTION.INPUT_BLUR:      return {        ...state,        touched: true,      };    default:      return state;  }};

and using it in reducer and type. Errors disappear BUT is it good idea or can I do this in a better way


React Native useRef with custom TextInput and TypeScript

$
0
0

I am getting the following warning on my custom input component:

'TextInput' refers to a value, but is being used as a type here. Did you mean 'typeof TextInput'?

When referencing it using useRef like so:

const lastNameRef = useRef<TextInput>(null)

Here's what TextInput looks like:

import React, { forwardRef } from "react"import {  TextInput as ReactTextInput,  TextInputProps as ReactTextInputProps,} from "react-native"import styled from "styled-components/native"import {  compose,  space,  SpaceProps,  color,  ColorProps,  layout,  LayoutProps,  flexbox,  FlexboxProps,  border,  BorderProps,  position,  PositionProps,  background,  BackgroundProps,  typography,  TypographyProps,} from "styled-system"export type TextInputProps = ReactTextInputProps &  SpaceProps &  ColorProps &  LayoutProps &  FlexboxProps &  BorderProps &  PositionProps &  BackgroundProps &  TypographyPropsconst StyledTextInput = styled.TextInput<TextInputProps>`  ${compose(    space,    color,    layout,    flexbox,    border,    position,    background,    typography,  )};`export const TextInput = forwardRef<ReactTextInput, TextInputProps>(  (    {      fontFamily = "body",      fontWeight = "regular",      fontSize = 1,      color = "text",      ...rest    },    ref,  ) => {    return (<StyledTextInput        {...{ ref, fontFamily, fontWeight, fontSize, color, ...rest }}      />    )  },)

I am forwarding the reference, which is what should get rid of that warning.

Any suggestions?

Converting Class based js component to typescript component with dynamic props destructuring

$
0
0

I have a class based component like this

class ArInput extends React.Component {  render() {    const { shadowless, success, error } = this.props;    const inputStyles = [      styles.input,      !shadowless && styles.shadow,      success && styles.success,      error && styles.error,      {...this.props.style}    ];    return (<Input        placeholder="write something here"        placeholderTextColor={argonTheme.COLORS.MUTED}        style={inputStyles}        color={argonTheme.COLORS.HEADER}        iconContent={<Icon            size={14}            color={argonTheme.COLORS.ICON}            name="link"            family="AntDesign"          />        }        {...this.props}      />    );  }}

I'm trying to convert above class to functional based component with react hooks.This is the best I came up with in typescript

const ArInput =({ shadowless, success, error, style }:any)=> {    const inputStyles = [      styles.input,      !shadowless && styles.shadow,      success && styles.success,      error && styles.error,      {...style}    ];    return (<Input        placeholder="write something here"        placeholderTextColor={argonTheme.COLORS.MUTED}        style={inputStyles}        color={argonTheme.COLORS.HEADER}        iconContent={<Icon            size={14}            color={argonTheme.COLORS.ICON}            name="link"            family="AntDesign"          />    }    { ...shadowless, ...success, ...error, ...style }  />);

}

but I'm getting an error on this line { ...shadowless, ...success, ...error, ...style }

The error is Expression expected.ts(1109)

In javascript code this the respectful line is {...this.props}

How can I convert my javascript class to typescript ?

And am I correct with the way I converted this line {...this.props.style} in javascript code ?

Javascript: Unexpected token { - occurs when try to import custom class in typescript file into javascript file

$
0
0

I am writing simple CLI scripts for react-native project. But I am not available to import class from typescript to javascript. It throw me following error.

import { TestResult } from './src/lib/modules/test-result';
SyntaxError: Unexpected token {...

package.json

..."script": {..."formular:convert": "node convertor.js"...}...

convertor.js

import {TestResult} from './src/lib/models/test-result';...

test-result.ts

import uuid from 'uuid/v4';import { Exception } from '../../errors';import { OilTypes, RawMaterialTypes } from '../oils';import { CalculatedResult } from './calculated-result';import { DeviceSettings } from './device-settings';import { DeviceStatus } from './device-status';import { DisplayedResult } from './displayed-result';import { Measurement } from './measurement';import { PhoneInfo } from './phone-info';import { PrimaryCompound } from './primary-compound';export class TestResult {    constructor(        public id: string = uuid(),        public createdAt: Date = new Date(),        public updatedAt: Date = new Date(),        public errors: Exception[] = [],        public alias: string = '',        public analyteTemp: number = 75,        public flowerWeight: number = 0,        public hidden: boolean = false,        public note: string = '',        public oilType: OilTypes = OilTypes.OliveOil,        public primaryCompound: PrimaryCompound = PrimaryCompound.UNDEFINED,        public units: string = '',        public user: string = '',        public air310Meas: Measurement = new Measurement(),        public air280Meas: Measurement = new Measurement(),        public analyte310Meas: Measurement = new Measurement(),        public analyte280Meas: Measurement = new Measurement(),        public calculated: CalculatedResult = new CalculatedResult(),        public displayed: DisplayedResult = new DisplayedResult(),        public status: DeviceStatus = new DeviceStatus(),        public settings: DeviceSettings = new DeviceSettings(),        public phoneInfo: PhoneInfo = new PhoneInfo(),        public rawMaterialType: RawMaterialTypes = RawMaterialTypes.Isolate,    ) {    }}

tsconfig.json

{"compilerOptions": {        /* Basic Options */"target": "es5",                       /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */"module": "commonjs",                  /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */        // "lib": [],                             /* Specify library files to be included in the compilation. */"allowJs": true,                       /* Allow javascript files to be compiled. *///        "checkJs": true,                       /* Report errors in .js files. */"jsx": "react",                 /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */                            /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */"removeComments": true,                /* Do not emit comments to output. */"noEmit": true,                        /* Do not emit outputs. */        /* Strict Type-Checking Options */"strict": true,                        /* Enable all strict type-checking options. */        /* Additional Checks */"noUnusedLocals": true,                /* Report errors on unused locals. */"noUnusedParameters": true,            /* Report errors on unused parameters. */"noImplicitReturns": true,             /* Report error when not all code paths in function return a value. */"noFallthroughCasesInSwitch": true,    /* Report errors for fallthrough cases in switch statement. */        /* Module Resolution Options */"moduleResolution": "node",            /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */"baseUrl": "./",                       /* Base directory to resolve non-absolute module names. */"types": [                             /* Type declaration files to be included in compilation. */"jest","mocha","detox"        ],"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'. */        /* Experimental Options */"experimentalDecorators": true,        /* Enables experimental support for ES7 decorators. */"emitDecoratorMetadata": true,         /* Enables experimental support for emitting type metadata for decorators. */"skipLibCheck": true,                  /* Skip type checking of declaration files. Requires TypeScript version 2.0 or later. */"forceConsistentCasingInFileNames": true,/* Disallow inconsistently-cased references to the same file. */"resolveJsonModule": true              /* Include modules imported with '.json' extension. Requires TypeScript version 2.9 or later. */    },"exclude": ["node_modules","babel.config.js","metro.config.js","jest.config.js"    ]}

I stuggled to find the solution, and found some answers here and there, but all of them doesn't work.

Thanks for your help.

How to pass all props to styled component in React Native with TypeScript?

$
0
0

I have a styled component:

const Wrapper = styled.View`  align-items: center;  flex-direction: row;`;

I have a component which is using this styled component:

interface ProfileInfoBar extends ViewProps {}const ProfileInfoBar: React.FC<ProfileInfoBar> = ({ ...rest }) => {  return (<Wrapper {...rest}><Avatar firstname="A" lastname="B" size={60} /></Wrapper>  );};

But I am getting an error when trying to pass rest to Wrapper:

No overload matches this call. Overload 1 of 2, '(props:Pick<Pick<ViewProps & RefAttributes, "hitSlop" | "onLayout" |"pointerEvents" | "removeClippedSubviews" | "style" | "testID" |"nativeID" | ... 48 more ... | "key"> & Partial<...>, "hitSlop" | ...54 more ... | "key"> & { ...; } & { ...; } & { ...; }):ReactElement<...>', gave the following error.Type '{ children: Element[]; hitSlop?: Insets | undefined; onLayout?: ((event: LayoutChangeEvent) => void) | undefined;pointerEvents?: "none" | "auto" | "box-none" | "box-only" | undefined;... 48 more ...; accessibilityIgnoresInvertColors?: boolean |undefined; }' is not assignable to type 'Pick<Pick<ViewProps &RefAttributes, "hitSlop" | "onLayout" | "pointerEvents" |"removeClippedSubviews" | "style" | "testID" | "nativeID" | ... 48more ... | "key"> & Partial<...>, "hitSlop" | ... 54 more ... |"key">'.Types of property 'style' are incompatible.

enter image description here

I can't understand how to pass all props to styled component. Any ideas?

Get internet speed in React using image download

$
0
0

I am trying to calculate the internet speed but I get a small value. This is the code:

useEffect(() =>     var imageAddr = "../../img/noventi-logo.png" +"?n=" + Math.random();    var startTime: number, endTime;    var downloadSize = 200000;    var download = new Image();    startTime = (new Date()).getTime();    download.src = imageAddr;    window.setTimeout(      download.onload = function () {        endTime = (new Date()).getTime();        showResults(endTime, startTime, downloadSize);    }, 1);,[]) function showResults(endTime: number, startTime: number, downloadSize: number) {    var duration = (endTime - startTime) / 1000;    var bitsLoaded = downloadSize * 8;    var speedBps: any = (bitsLoaded / duration).toFixed(2);    var speedKbps: any = (speedBps / 1024).toFixed(2);    var speedMbps = (speedKbps / 1024).toFixed(2);    alert("Your connection speed is: \n" +           speedBps +" bps\n"   +           speedKbps +" kbps\n" +           speedMbps +" Mbps\n" );}

And as a result I get only values like 0,6 Mbps.

PLEASE HELP ME

Viewing all 6287 articles
Browse latest View live


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