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

how can i use default props in react.js or react-native?

$
0
0

For example. i have Feeds and Upload Components. also i have ImageFeedList component in Feeds, Upload Components

(Feed.js)

import React, {useContext, useState, useEffect} from 'react';import {StackNavigationProp} from '@react-navigation/stack';import {RandomUserDataContext} from '~/Context/RandomUserData';import ImageFeedList from '~/Components/ImageFeedList';type NavigationProp = StackNavigationProp<FeedsTabParamList, 'Feeds'>;interface Props { navigation: NavigationProp; }   const Feeds = ({navigation}: Props) => {   const {getMyFeed} = useContext(RandomUserDataContext);   const [feedList, setFeedList] = useState<Array<IFeed>>([]);   const [loading, setLoading] = useState<boolean>(false);  useEffect(() => {    setFeedList(getMyFeed(24));  }, []);  return (<ImageFeedList      feedList={feedList}      loading={loading}      onRefresh={() => {      setLoading(true);      setTimeout(() => {      setFeedList(getMyFeed(24));      setLoading(false);      }, 2000);      }}     onEndReached={() => {     setFeedList([...feedList, ...getMyFeed(24)]);      }}     onPress={() => {     navigation.navigate('FeedListOnly');     }}      />     );      };   export default Feeds;

(Upload.js)

 import React, {useContext, useState, useEffect} from 'react'; import {RandomUserDataContext} from '~/Context/RandomUserData'; import ImageFeedList from '~/Components/ImageFeedList';  const Upload = () => {  const {getMyFeed} = useContext(RandomUserDataContext);  const [feedList, setFeedList] = useState<Array<IFeed>>([]);  const [loading, setLoading] = useState<boolean>(false);  useEffect(() => {  setFeedList(getMyFeed(24));  }, []);     return (<ImageFeedList    feedList={feedList}    loading={loading}    onRefresh={() => {    setLoading(true);    setTimeout(() => {    setFeedList(getMyFeed(24));    setLoading(false);    }, 2000);  }}  onEndReached={() => {    setFeedList([...feedList, ...getMyFeed(24)]);  }}  /> ); }; export default Upload;

(ImageFeedList.js)

import React from 'react';import {FlatList,Image,Dimensions,NativeSyntheticEvent,NativeScrollEvent,} from 'react-native';  import styled from 'styled-components/native';  interface Props { id?: number; bounces?: boolean; scrollEnabled?: boolean; feedList: Array<IFeed>; loading?: boolean; onRefresh?: () => void;onEndReached?: () => void;  onScroll?: (event: NativeSyntheticEvent<NativeScrollEvent>) => void; onPress?: () => void;}const ImageFeedList = ({ id, bounces = true, scrollEnabled = true,feedList,loading,onRefresh,onEndReached,onScroll,onPress,}: Props) => {const width = Dimensions.get('window').width;const imageWidth = width / 3;return (<FlatList  data={feedList}  style={{width}}  keyExtractor={(item, index) => {    return `image-feed-${id}-${index}`;  }}  showsVerticalScrollIndicator={false}  scrollEnabled={scrollEnabled}  bounces={bounces}  numColumns={3}  onRefresh={onRefresh}  onEndReached={onEndReached}  onEndReachedThreshold={0.5}  refreshing={loading}  onScroll={onScroll}  scrollEventThrottle={400}  renderItem={({item, index}) => (<ImageContainer      style={{        paddingLeft: index % 3 === 0 ? 0 : 1,        paddingRight: index % 3 === 2 ? 0 : 1,      }}      onPress={onPress}><Image        source={{uri: item.images[0]}}        style={{width: imageWidth, height: imageWidth}}      /></ImageContainer>  )}/>    );    };   export default ImageFeedList;

what i want to ask is that in Feeds Component i have OnPress and i can pass onPress to ImageFeedList component as Props but there is no onPress props in Upload Component. however error is not gonna happen eventhough there is no onPress in Upload because i have a

interface Props {onPress?: () => void; }

this code i define onPress Props in In ImageFeedList components it meanse if i don't get Props onPress then it's fine

i can use this default props in typeScript

but my question is that how can i use default props in react and react-native other than typeScript??

is there way??


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

global.HermesInternal - Property 'HermesInternal' does not exist on type 'Global & typeof globalThis'

$
0
0

I have the code below, auto generated with:

$ react-native init RepeatAloud

App.tsx

/** * Sample React Native App * https://github.com/facebook/react-native * * @format * @flow strict-local */import React from 'react';import {  SafeAreaView,  StyleSheet,  ScrollView,  View,  Text,  StatusBar,} from 'react-native';import {  Header,  LearnMoreLinks,  Colors,  DebugInstructions,  ReloadInstructions,} from 'react-native/Libraries/NewAppScreen';const App: () => React.ReactNode = () => {  return (<><StatusBar barStyle="dark-content" /><SafeAreaView><ScrollView          contentInsetAdjustmentBehavior="automatic"          style={styles.scrollView}><Header />          {global.HermesInternal == null ? null : (<View style={styles.engine}><Text style={styles.footer}>Engine: Hermes</Text></View>          )}<View style={styles.body}><View style={styles.sectionContainer}><Text style={styles.sectionTitle}>Step One</Text><Text style={styles.sectionDescription}>                Edit <Text style={styles.highlight}>App.js</Text> to change this                screen and then come back to see your edits.</Text></View><View style={styles.sectionContainer}><Text style={styles.sectionTitle}>See Your Changes</Text><Text style={styles.sectionDescription}><ReloadInstructions /></Text></View><View style={styles.sectionContainer}><Text style={styles.sectionTitle}>Debug</Text><Text style={styles.sectionDescription}><DebugInstructions /></Text></View><View style={styles.sectionContainer}><Text style={styles.sectionTitle}>Learn More</Text><Text style={styles.sectionDescription}>                Read the docs to discover what to do next:</Text></View><LearnMoreLinks /></View></ScrollView></SafeAreaView></>  );};const styles = StyleSheet.create({  scrollView: {    backgroundColor: Colors.lighter,  },  engine: {    position: 'absolute',    right: 0,  },  body: {    backgroundColor: Colors.white,  },  sectionContainer: {    marginTop: 32,    paddingHorizontal: 24,  },  sectionTitle: {    fontSize: 24,    fontWeight: '600',    color: Colors.black,  },  sectionDescription: {    marginTop: 8,    fontSize: 18,    fontWeight: '400',    color: Colors.dark,  },  highlight: {    fontWeight: '700',  },  footer: {    color: Colors.dark,    fontSize: 12,    fontWeight: '600',    padding: 4,    paddingRight: 12,    textAlign: 'right',  },});export default App;

where I get the the following error:

Property 'HermesInternal' does not exist on type 'Global & typeof globalThis'.

as you can see here:

enter image description here

Is there any way to handle this?

Thanks!

TypeDoc how do i generate documentation for internal functions

$
0
0

I'm trying to generate documentation for my TypeScript/React Native project. But from what I've seen you need to add an export to a function for TypeDoc to generate documentation. However, most of my functions are inside components so its not possible to add export to them. Example:

const TVShowDetailsScreen: React.FC<Props> = (props: any) => {  const user: firebase.User = firebase.auth().currentUser;  const watchlistRef = firebase.firestore().collection("Watchlist");  const { email } = user;  const [data, setData] = useState<TVShowDetails>();  const { show } = props.route.params;  useEffect(() => {    init();  }, []);  const init = async () => {    const { data } = await getTVShowDetails(show.id);    setData(data);  };  if (!data) {    return (<View        style={{          height: Dimensions.get("window").height,          width: Dimensions.get("window").width,          backgroundColor: "#18181b",        }}></View>    );  }  const renderGenres = () => {    return data.genres.map((o) => {      return (<S.GenreText key={o.id} style={{ color: "white", top: 10 }}>          {o.name}</S.GenreText>      );    });  };  async function handleAddToWatchList() {    const watchListSnapshot = await watchlistRef      .where("userId", "==", email)      .get();    const watchlistId = watchListSnapshot.docs[0].id;    const documentRef = watchlistRef.doc(watchlistId);    data.seasons.forEach(async (s) => {      let season = {        [s.season_number]: {},      };      let episodesList: {        episodeNumber: number;        episodeName: string;        season: number;      }[] = [];      const { data: seasonData } = await getTVShowSeasonDetails(        data.id,        s.season_number      );      const { episodes } = seasonData;      const seasonEpisodes = episodes.filter(        (e) => e.season_number === s.season_number      );      seasonEpisodes.forEach((e) => {        const episodeObject = {          episodeNumber: e.episode_number,          episodeName: e.name,          season: e.season_number,          imdb: e.vote_average,          date: e.air_date,          overview: e.overview,          id: e.id,          stillPath: e.still_path,        };        episodesList.push(episodeObject);        season[s.season_number] = episodesList;      });      documentRef.set(        {          tvShows: {            [data.name]: {              title: data.name,              overview: show.overview,              backdrop: "http://image.tmdb.org/t/p/w500" + data.backdrop_path,              id: data.id,              seasons: season,            },          },        },        { merge: true }      );    });    ToastAndroid.showWithGravity("Added to Watchlist!",      ToastAndroid.SHORT,      ToastAndroid.CENTER    );  }  const renderSeasonTabs = () => {    return data.seasons.map((s) => {      return (<Tab          key={s.season_number}          heading={<TabHeading style={{ backgroundColor: "#880421" }}><Text>{s.season_number}</Text></TabHeading>          }><TVShowSeasonTab seasonNumber={s.season_number} showId={data.id} /></Tab>      );    });  };  return (<View      style={{        flex: 1,        justifyContent: "center",        alignItems: "center",        backgroundColor: "#18181b",      }}><StatusBar hidden translucent backgroundColor="transparent" /><ScrollView        style={{ flex: 1 }}        contentContainerStyle={{          width: Dimensions.get("window").width,        }}><Image          style={{ height: 281, width: 500 }}          source={{            uri: "http://image.tmdb.org/t/p/w500" + data.backdrop_path,          }}        /><S.AddToWatchListButton onPress={handleAddToWatchList}><S.ButtonText>+</S.ButtonText></S.AddToWatchListButton><Text          style={{            color: "white",            position: "absolute",            top: 210,            left: 10,            fontSize: 30,          }}>          {data.name}</Text>        {renderGenres()}<Text          style={{            fontSize: 20,            top: 20,            left: 20,            color: "#b9042c",          }}>          Synposis</Text><Text          style={{            margin: 20,            color: "white",          }}>          {show.overview}</Text><Text          style={{            fontSize: 20,            left: 20,            color: "#b9042c",          }}>          IMDB</Text><Text          style={{            left: 20,            color: "white",          }}>          {data.vote_average}</Text><S.Header>Seasons</S.Header><Tabs style={{ marginTop: 15 }}>{renderSeasonTabs()}</Tabs></ScrollView></View>  );};export default TVShowDetailsScreen;

Here i'd like to generate documentation for the renderGenres function, the handleAddToWatchList function etc. Is it possible with TypeDoc? Or is there an alternate doc generator that i can use?

React Hook Forms How to pass the errors as a props using Typescript

$
0
0

I'm defining a useForm.

const { handleSubmit, control, errors } = useForm<{email: string}>();

Now I'm creating a seperate component that will the input and I'm going to pass the useForm props i created above.

This how that Components look like.

type Props<T> = {  name: FieldName<T>;  control: Control<T>;  errors: FieldErrors<T>;};const ControlTextInput = <T extends {}>({  name,  control,  errors,}: Props<T>) => {  return (<Controller    name={name}    control={control}    rules={{      required:'this is required',    }}    render={({ onChange }) => (<><TextInput                onChangeText={(text) => {                onChange(text);                }}            />            {/* Show my error here */}            {errors.email && (<Text style={{ color: "red" }}>                    {errors.email?.message}</Text>            )}</>    )}  />  );};

I want to use the component like this.

<ControlTextInput<AnyObject>                    name="email"                    errors={errors}                    control={control}                  />

I get this error when i hover over the errors.emailenter image description here

Calling a children method of a functional component from parent

$
0
0

I am not using class, I'd like to learn how to do it manually. I am dealing with login screen.https://snack.expo.io/@ericsia/call-function-from-child-componentIf you want to show me your code, you need to save and share the link. So I wanted a functional component for display textbox (assume ChildComponent as the function name, so export ChildComponent).
So in Parent/Screen1 I have something like this right?

import * as React from 'react';import { Text, View, StyleSheet, TouchableOpacity } from 'react-native';import Constants from 'expo-constants';// You can import from local filesimport ChildComponent from './components/ChildComponent';export default function App() {  function checkSuccess()  {    // call helloWorld from here  }  return (<View style={styles.container}><ChildComponent /><TouchableOpacity style={styles.button}        onPress={ checkSuccess } ><Text>helloWorld ChildComponent</Text></TouchableOpacity></View>  );}const styles = StyleSheet.create({  container: {    flex: 1,    justifyContent: 'center',    paddingTop: Constants.statusBarHeight,    backgroundColor: '#ecf0f1',    padding: 8,  },  button: {    alignItems: "center",    backgroundColor: "#DDDDDD",    padding: 10  },});

so if the result is invalid right, I wanted to display a tiny red error message.something like thisMy approach is if I can call a function from the ChildComponent then I may still solve it.
I googled it and most of the solution provided is for class.I tried useEffectReact.createRefuseImperativeHandle but I didn't get it work.
for start, i am just trying to call the helloWorld()

import * as React from 'react';import { TextInput , View, StyleSheet, Image } from 'react-native';export default function ChildComponent() {  function helloWorld()  {    alert("Hello World");  }  return (<TextInput placeholder="Try to call helloWorld from App.js"/>);}

Another question, if I have a textbox in my ChildComponent how do I retrieve the text/value from parent?

How to setup/use ref correctly for a themed functional component in typescript + react native

$
0
0

Main Goal: I have two TextInput and I want to simulate the return click on first textInput to set focus to the next textInput.

Lets start with the setup (using typescript)

I have a themed TextInput with some color settings as shown below. I setup/use the forwardRef to pass-on the ref if provided. Of what I could read, this seems to be the right way. but maybe this is wrong.

export type TextInputProps = ThemeProps & RNTextInput['props'];export const TextInput = React.forwardRef<RNTextInput, TextInputProps>((props, ref) => {...return <RNTextInput style={[{ backgroundColor, color }, style]} {...otherProps} ref={ref} />;}

Now on my screen, I am using this object and on the completion of typing on first input, I wanted to set focus on this one. The code looks like this..

const inputSecound = React.useRef<typeof TextInput>();const handleFirstTextComplete = () => {    inputSecound.current.focus() // This does not work}...<TextInput onSubmitEditing={handleFirstTextComplete} ...><TextInput ... ref={inputSecound}> //This also complains

Any idea how to achieve this correctly in functional components + custom components + typescript.

A sample snack is available here if you wants to see the complete setup in action.https://snack.expo.io/@varesh.tapadia/useref-and-useforwardref

How to setup multiple environment Dev and Prod for React Native Typescript?

$
0
0

In My application, I am using two different API's for development and production. I want to Implement Like whenever If I pass the command yarn dev iOS then build will generate with development API, Same as well If I pass the command yarn prod iOS build will generate with production API. How to achieve this?

I have tried using react-native-dotenv but not getting much clear idea.


expo typescript app how to correctly type navigation propto avoid. : "t 'navigation' implicitly has an 'any' type"

$
0
0

I use in my expo app react-navigation and in a class component, I want to navigate to another screen ...
I get the props in a function this way :

     private signUp({navigation}): void {         // eslint-disable-next-line no-console         console.log('navigation', navigation);       navigation.navigate('CheckSteps')       }    ... signUp={ () => this.signUp(this.props)} />

But at the level of my signUp function, on the navigation I have a typing error:

Binding element 'navigation' implicitly has an 'any' type

How to remove this error correctly ??

react-native 0.63.4 with Hermes (android): Crash on startup

$
0
0

I've been building an app in React-Native. It initially was a 0.60 project, and over the course of development I have upgraded it several times and not it's on 0.63.4.

I noticed that, when running a release build on Android, the app feels really slow. It feels like it's eating up all the phone's memory. When I run it in Android Studio and attach a profiler, all seems normal though (+- 15% CPU usage, 128mb memory usage).

I tried adding Hermes to my app to see if it would make any difference, but as soon as I set the enableHermes parameter to true, clean & build, my app crashes without any error message (after a successful build) as soon as it launches.

I then went to React-Native's docs, where an alert said that each Hermes release is aimed at a specific RN version. Fine, I thought. React 0.63.x has Hermes version 0.5.3. Whenever I go to my yarn.lock and set hermes-engine "0.5.3", it said it cannot find it and asks me which version I want to install instead.

I'm puzzled.

QuestionWhat version of Hermes is appropriate for React-Native 0.63.4, and How do I add it appropriately to prevent the no-error-message crashes I'm getting now?

Any guidance would be highly appreciated.

Define State type on react native?

$
0
0

I'm calling a movie API, and want the searchValue to be updated everytime I write in the search bar. However, it seems like I need to define the "setSearchValue" as I'm using typescript. How can I do it?

import React from 'react';import { useState, useEffect } from 'react';import { ScrollView } from 'react-native';import MovieList from './components/MovieList'import Search from './components/Search';const App: React.FC = () => {    const [movies, setMovies] = useState([]);    const [searchValue, setSearchValue] = useState('');    const getMovieRequest = async () => {        const url = `http://www.omdbapi.com/?s=${searchValue}&apikey=520a7faf`;        const response = await fetch(url);        const responseJson = await response.json();        if(responseJson.Search) {            setMovies(responseJson.Search);        }    };    useEffect(() => {        getMovieRequest(searchValue);    }, [searchValue]);    console.log(movies);    return (<><Search searchValue={searchValue} setSearchValue={setSearchValue} /><ScrollView><MovieList movies={movies} /></ScrollView></>    );};export default App;

And here is the Search component:

import React from 'react';import { View, TextInput } from 'react-native';interface Props {    value: string;    searchValue: string;}const Search: React.FC<Props> = (props) => {    return (<View><TextInput            placeholder="Search here"           value={props.value}           onChange={(event) => props.setSearchValue(event.target.value)}           /></View>    );}export default Search;

I'm getting the error: "Property 'setSearchValue' does not exist on type 'PropsWithChildren'."

unable to resolve ./../packages.json from node_modules/

$
0
0

I am unable to compile my react-native JS bundle, as I am repeatedly getting the above error, but I don't think this has to be related to any package, although I doubt I am having some configuration issue with either babel or typescript

My tsconfig.json looks something like this

{"compilerOptions": {    /* Basic Options */"target": "es6" /* 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'. */,"allowJs": true /* Allow javascript files to be compiled. */,    // "checkJs": true /* Report errors in .js files. */,"jsx": "react-native" /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */,"noEmit": true /* Do not emit outputs. */,"strict": true /* Enable all strict type-checking options. */,"moduleResolution": "node" /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */,"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'. */,"baseUrl": ".","paths": {"*": ["App/*"],"Assets": ["App/Assets"],"Components": ["App/Components"],"Config": ["App/Config"],"Containers": ["App/Containers"],"Fixtures": ["App/Fixtures"],"Images": ["App/Images"],"Navigation": ["App/Navigation"],"Sagas": ["App/Sagas"],"Services": ["App/Services"],"Themes": ["App/Themes"],"types": ["types"]    }},"exclude": ["node_modules"]

}

And my babelrc looks something liks this

"presets": ["module:metro-react-native-babel-preset","@babel/preset-typescript"    ],"plugins": [        ["@babel/plugin-transform-flow-strip-types"],        ["@babel/plugin-proposal-decorators",            {"legacy": true            }        ],        ["@babel/plugin-proposal-class-properties",            {"loose": true            }        ],        ["module-resolver",            {"extensions": [".js", ".ios.js", ".android.js", ".ts", ".tsx", ".json"],"alias": {"Assets": "./App/Assets","Components": "./App/Components","Config": "./App/Config","Containers": "./App/Containers","Fixtures": "./App/Fixtures","Images": "./App/Images","Navigation": "./App/Navigation","Sagas": "./App/Sagas","Services": "./App/Services","Themes": "./App/Themes","types": "./types"                }            }        ]    ],"env": {"production": {"plugins": ["ignite-ignore-reactotron", "transform-remove-console"]        }    }}

babel packages being used

"@babel/cli": "^7.6.0","@babel/core": "^7.6.2","@babel/plugin-proposal-class-properties": "^7.12.1","@babel/plugin-proposal-decorators": "^7.12.1","@babel/plugin-proposal-object-rest-spread": "^7.12.1","@babel/plugin-transform-flow-strip-types": "^7.12.10","@babel/preset-flow": "^7.0.0","@babel/preset-typescript": "^7.12.7","@babel/runtime": "^7.6.2","babel-eslint": "^10.1.0","babel-jest": "^24.9.0","babel-plugin-functional-hmr": "^1.0.24","babel-plugin-ignite-ignore-reactotron": "^0.3.0","babel-plugin-module-resolver": "^4.1.0","babel-plugin-transform-remove-console": "^6.9.4","babel-preset-es2015": "^6.18.0","babel-preset-react-native": "^5",

I am not able to connect the dots at all that what exactly going wrong,not even deleting packager cache of react-native either helping here

Property 'value' is missing in type '{ searchValue: string; setSearchValue: Dispatch; }' but required in type 'Props'

$
0
0

I'm using react native with typescript to render some movie posters from an API when the movie title is writen on the search bar. But when I try to render the search bar on my app I get this error:

Property 'value' is missing in type '{ searchValue: string; setSearchValue: Dispatch<SetStateAction>; }' but required in type 'Props'.

And under it:

Search.tsx(7, 5): 'value' is declared here.

Here is the App code:

import React from 'react';import { useState, useEffect } from 'react';import { ScrollView } from 'react-native';import MovieList from './components/MovieList'import Search from './components/Search';import { Container } from './styles'const App: React.FC = () => {    const [movies, setMovies] = useState([]);    const [searchValue, setSearchValue] = useState('');    const getMovieRequest = async (searchValue) => {        const url = `http://www.omdbapi.com/?s=${searchValue}&apikey=520a7faf`;        const response = await fetch(url);        const responseJson = await response.json();        if (responseJson.Search) {            setMovies(responseJson.Search);        }    };    useEffect(() => {        getMovieRequest(searchValue);    }, [searchValue]);    console.log(movies);    return (<><Container><Search searchValue={searchValue} setSearchValue={setSearchValue} /><ScrollView><MovieList movies={movies} /></ScrollView></Container></>    );};export default App;

And the search bar component:

import React from 'react';import { View, TextInput } from 'react-native';interface Props {    searchValue: string;    setSearchValue:(string) => void;    value: any;}const Search: React.FC<Props> = (props) => {    return (<View><TextInput            placeholder="Pesquise aqui"           value={props.value}           onChange={(event: any) => props.setSearchValue(event.target.value)}           /></View>    );}export default Search;

Problems with react-native-svg-transformer and typescript

$
0
0

I decided to add typescript in a existing project and have a issue when a i works with import of .svg like a this

import Icon from "../../../assets/Icon.svg";

i tried configure metro.config.js

const { getDefaultConfig } = require("metro-config");module.exports = (async () => {  const {    resolver: { sourceExts, assetExts },  } = await getDefaultConfig();  return {    transformer: {      babelTransformerPath: require.resolve("react-native-svg-transformer"),    },    resolver: {      assetExts: assetExts.filter((ext) => ext !== "svg"),      sourceExts: [...sourceExts, "svg"],    },  };})();

and add a declarations file

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

but it's not work for me, and i get the error

in the terminal

in the phone

Compressing input file to .gz (gzip) file in React application

$
0
0

I am trying to compress an uploaded file to gzip (.gz) in my react application. Tried to do it using JSZIP package but unable to achieve the results. Is anyone aware how to achieve it?


React Native State Updated when it should not

$
0
0

I have filterData which comes from a controller, so i set filterData to options, for the UI,Like this

const [state, setState] = React.useState({    options: filterData,  });

filter data is this

[{"List": [{"Name": "TEST1", "isSelected": false}, {"Name": "TEST2", "isSelected": false}, {"Name": "TEST3", "isSelected": true}], "Type": "Type"},{"List": [{"Name": "TEST4", "isSelected": false}, {"Name": "TEST5", "isSelected": false}, {"Name": "TEST6", "isSelected": true}], "Type": "Type2"}]

I render it in a flatlist and then map the List, this is the code for my flatlist

<FlatList        style={{flex: 1, backgroundColor: colors.white}}        data={state.options}        keyExtractor={(_, index) => index.toString()}        renderItem={({item, index}) => {          return (<View style={{marginBottom: widthPercentageToDP(5)}}><Text>                {item.Type}</Text><View                style={{                  flexDirection: 'row',                  flexWrap: 'wrap',                }}><View                  style={{                    marginRight: 8,                    marginBottom: 8,                  }}><TouchableOpacity><Text>                      Select All</Text></TouchableOpacity></View>                {item.List.map((e: any, idx: number) => (<View                    key={idx}><TouchableOpacity                      onPress={() =>                        handleSelect(idx, item.Type)                      }><Text>                        {e.Name}</Text></TouchableOpacity></View>                ))}</View></View>          );        }}</View></View>      );     }}   />

as you can see from above, i will have some buttons. And if the button is clicked, it will call handleSelect function. which is this

const handleSelect = async (idx: number, type: string) => {    let arr = [...state.options];    arr.map((item) => {      if (item.Type === type) {        item.List[idx].isSelected = !item.List[idx].isSelected;      }    });    console.log(state.options)  };

i didnt change the state of the options like the code below, only console.log

setState((prevState) => ({      ...prevState,      options: arr,    }));

The problem is, in the log when i clicked and run that function, state.options will also change.it will have the same data as arr. Even filterData also change when i console.log in handleselect. I already checked my controller and it didnt trigger any function.Does anyone know why it update all of my variable?

Glitchy navigation when navigating to a stack screen in a different tab of material bottom navigation

$
0
0

As mentioned in the title, I have nested navigation stacks in my application as follow

const MainStackNavigation: React.FC = () => {  return (<Stack.Navigator      initialRouteName="ScreenZero"      headerMode="screen"><Stack.Screen        name="BottomStackNavigation"        component={BottomStackNavigation}      /><Stack.Screen        name="ScreenZero"        component={ScreenZero}      /></Stack.Navigator>  );};
const BottomNavigation: FC = () => {  return (<Tab.Navigator      initialRouteName="Home"      tabBarPosition="bottom"><Tab.Screen        name="Home"        component={HomeStack}      /><Tab.Screen        name="Setting"        component={SettingStack}      /></Tab.Navigator >  );};
const HomeStack: FC = () => {  return (<Stack.Navigator      initialRouteName="ScreenOne"><Stack.Screen name="ScreenOne" component={ScreenOne} /><Stack.Screen name="ScreenTwo" component={ScreenTwo} /></Stack.Navigator>  );};
const SettingStack: FC = () => {  return (<Stack.Navigator      initialRouteName="ScreenThree"><Stack.Screen name="ScreenThree" component={ScreenThree} /><Stack.Screen name="ScreenFour" component={ScreenFour} /></Stack.Navigator>  );};

Let's say if I'm in BottomNavigation -> SettingStack -> ScreenFour, and then I want to navigate to ScreenOne which is in the HomeStack. Instead of animating directly to ScreenOne, the application navigate first to HomeStack and then navigate to ScreenOne. So you can see we have this weird transition effect and it can get trippy to look at.

Is there any way I can do to make the transition more fluid? Putting the ScreenOne into HomeStack is not what I want because ScreenOne will be navigated from multiple screens in different stacks

react native : How can I change the following code to a function component with hooks?

$
0
0

How can I change the following code to a function component with hooks?In the following code I try to make a modal, but I need to change it to a function component .I would be happy to help with this.

export default class Example extends Component {  state = {    visibleModal: null,  };  _renderButton = (text, onPress) => (<TouchableOpacity onPress={onPress}><View style={styles.button}><Text>{text}</Text></View></TouchableOpacity>  );  _renderModalContent = () => (<View style={styles.modalContent}><Text>Hello!</Text>      {this._renderButton('Close', () => this.setState({ visibleModal: null }))}</View>  );  render() {    return (<View style={styles.container}>        {this._renderButton('A slower modal', () => this.setState({ visibleModal: 3 }))}<Modal isVisible={this.state.visibleModal === 1}>          {this._renderModalContent()}</Modal><Modal          isVisible={this.state.visibleModal === 3}          animationInTiming={2000}          animationOutTiming={2000}          backdropTransitionInTiming={2000}          backdropTransitionOutTiming={2000}>          {this._renderModalContent()}</Modal></View>    );  }}

React-native-svg loading animated svg file from url

$
0
0

I am using "react-native-svg": "^12.1.0" and am opening svg this way:

<SvgCssUri uri={imageURL} style={imageStyle} height={height} width={width} />

If the svg on url is animated, the animation is not shown in my application. If I click on the link and open it in browser it works as it should. Does anyone have any advice on this or already had this problem and solved it? Or if anyone knows if this npm is maybe not meant to load animated svg files?

Create a React Native app with no Typescript? (Could not get BatchedBridge)

$
0
0

I created a project with react native to try typescript, running this command:

npx react-native init --template react-native-template-typescript

Now, everytime I create a project just using "npx react-native init ", without the template, it won't work unless I use typescript. Even projects I had previosly created in react native only with javascript won't show up in the android studio virtual device.

I always get this error:

Could not get BatchedBridge, make sure your bundle is packaged correctly

I have already tried to install react-native again, created multiple new projects from scratch, ran "yarn", "yarn start", "yarn android". I have deleted node modules and installed everything again. I have cleaned the cache. Nothing seems to work.

I have react-native-cli: 2.0.1 and react-native: 0.63.4

Viewing all 6288 articles
Browse latest View live


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