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

How Platform.select({}) works?

$
0
0

I'm having configuration in build.gradle and info.plist which i need to get on run time using ▼

import { Platform } from 'react-native';import BuildConfig from 'react-native-build-config';

I have no issue while testing this on iPhone but gets undefined on Buildconfig when i execute this on Android, It make no sense that BuildConfig is undefined, though it's fetching Info.plist property which is wrong but it should point to property not to BuildConig, itself.
when it's running on Android it works perfectly for Android but failed on iOS part or on GlobalConfig.b.CFBundleURLTypes[0].CFBundleURLSchemes[1].

Failing scenarios:

 // Deeplinks -----------------------  public static readonly DEEPLINK_INTENT_HOST: string = Platform.select({    ios: BuildConfig.CFBundleURLTypes[0].CFBundleURLSchemes[1],    android: BuildConfig.INTENT_FILTER_HOST,    default: ''  });

//-----------------------------------------------------------------

// Deeplinks -----------------------      public static readonly DEEPLINK_INTENT_HOST: string =       Platform.select({        ios: (BuildConfig.CFBundleURLTypes || [])[0].CFBundleURLSchemes[1],        android: BuildConfig.INTENT_FILTER_HOST,        default: ''      });

//-----------------------------------------------------------------

  // Deeplinks -----------------------  public static b: any = BuildConfig;  public static readonly DEEPLINK_INTENT_HOST: string = Platform.select({    ios: GlobalConfig.b.CFBundleURLTypes[0].CFBundleURLSchemes[1],    android: GlobalConfig.b.INTENT_FILTER_HOST,    default: ''  });

Working scenarios:

  // Deeplinks -----------------------  public static readonly DEEPLINK_INTENT_HOST: string = Platform.OS == 'ios' ? BuildConfig.CFBundleURLType[0].CFBundleURLSchemes[1] : BuildConfig.INTENT_FILTER_HOST;

Render Content Dynamically from an array map function in React Native functional component and useState

$
0
0

I have a functional component to render a simple form with some input elements.

I want to be able to dynamically add input elements when the user click a button.Im using useState hook and created a onChange arrow func as follows:

  const [players, setPlayers] = useState<PlayerModel[]>([    { id: 0, firstName: "", lastName: "" },  ]);  const handleOnAddPlayerPress = () => {    let newPlayers = players;    newPlayers.push({ id: newPlayers[newPlayers.length - 1].id + 1, firstName: "", lastName: "" });    setPlayers(newPlayers);  } 

I'm rendering the players using array map function as follows:

{players.map((player, index) => {      return <Input key={index} label={`Player #${player.id}`} />;    })}

Im calling the onChange function when the user clicks the button as follows:

<Button  onPress={handleOnAddPlayerPress}  type="clear"  icon={<Icon      raised={true}      name="user-plus"      underlayColor="black"      type="font-awesome"      reverse    />  }></Button>

all together:

import React, { useState } from "react";import { ScrollView } from 'react-native';import { Overlay, Input, Button, Icon } from "react-native-elements";import { PlayerModel } from "../../models/PlayerModel";export namespace AddNewTournamentForm {  export interface Props {    isVisible: boolean;    onBackdropPress: () => void;  }}export const AddNewTournamentForm = (  props: AddNewTournamentForm.Props): JSX.Element => {  const [players, setPlayers] = useState<PlayerModel[]>([    { id: 0, firstName: "", lastName: "" },  ]);  const handleOnAddPlayerPress = () => {    let newPlayers = players;    newPlayers.push({ id: newPlayers[newPlayers.length - 1].id + 1, firstName: "", lastName: "" });    setPlayers(newPlayers);  }   return (<Overlay {...props} fullScreen><ScrollView>        ...        {players.map((player, index) => {          return <Input key={index} label={`Player #${player.id}`} />;        })}<Button          onPress={handleOnAddPlayerPress}          type="clear"          icon={<Icon              raised={true}              name="user-plus"              underlayColor="black"              type="font-awesome"              reverse            />          }></Button>        ...</ScrollView></Overlay>  );};

However the layout doesn't seem to be re-rendering itself when a change occur.Another strange thing is that when I go out of this overlay and go back, only then I see the updated amount of input elements according to the num of players (which is strange because if I go out and in to the Overlay the state should be initiated).

Any suggestion? :)

How Platform.select({}) works? getting undefined BuildConfig when executing on iOS

$
0
0

I'm having configuration in build.gradle and info.plist which i need to get on run time using ▼

import { Platform } from 'react-native';import BuildConfig from 'react-native-build-config';

I have no issue while testing this on iPhone but gets undefined on Buildconfig when i execute this on Android, It make no sense that BuildConfig is undefined, though it's fetching Info.plist property which is wrong but it should point to property not to BuildConig, itself.
when it's running on Android it works perfectly for Android but failed on iOS part or on GlobalConfig.b.CFBundleURLTypes[0].CFBundleURLSchemes[1].

Failing scenarios:

 // Deeplinks -----------------------  public static readonly DEEPLINK_INTENT_HOST: string = Platform.select({    ios: BuildConfig.CFBundleURLTypes[0].CFBundleURLSchemes[1],    android: BuildConfig.INTENT_FILTER_HOST,    default: ''  });

//-----------------------------------------------------------------

// Deeplinks -----------------------      public static readonly DEEPLINK_INTENT_HOST: string =       Platform.select({        ios: (BuildConfig.CFBundleURLTypes || [])[0].CFBundleURLSchemes[1],        android: BuildConfig.INTENT_FILTER_HOST,        default: ''      });

//-----------------------------------------------------------------

  // Deeplinks -----------------------  public static b: any = BuildConfig;  public static readonly DEEPLINK_INTENT_HOST: string = Platform.select({    ios: GlobalConfig.b.CFBundleURLTypes[0].CFBundleURLSchemes[1],    android: GlobalConfig.b.INTENT_FILTER_HOST,    default: ''  });

Working scenarios:

  // Deeplinks -----------------------  public static readonly DEEPLINK_INTENT_HOST: string = Platform.OS == 'ios' ? BuildConfig.CFBundleURLType[0].CFBundleURLSchemes[1] : BuildConfig.INTENT_FILTER_HOST;

TypeError: Cannot read property 'additionalData' of undefined, js engine: hermes

$
0
0

additionalData can bee a object or undefined. And same with validation not print in console. Occurs this error "TypeError: Cannot read property 'additionalData' of undefined, js engine: hermes"

if print the notification variable on the console, the variable "additionalData" appears as follows: { "payload": "additionalData": [object] }

const onReceived = useCallback((notification: ReceivedNotification) => {const { additionalData } = notification.payload;if (additionalData) {    console.log(additionalData);  }}, []);useEffect(() => {  OneSignal.init('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX');  OneSignal.addEventListener('opened', onReceived);  OneSignal.addEventListener('ids', onIds);  OneSignal.inFocusDisplaying(2);  OneSignal.clearOneSignalNotifications();}, [onIds, onReceived]);

Recorder not working in react-native-audio-recorder-player

$
0
0

I am trying to use the package as mentioned, and here is my code, not sure why it seems to have recorded, but when I click play, no sound can be heard, and even I drag the file to another music player, it can't play the file. I have some basic setup just follow the Example in git from the package.

const RecordingScreen = () => {  const [audio, setAudio] =useState({    recordSecs:0,    recordTime:'00:00:00',    currentPositionSec: 0,    currentDurationSec: 0,    playTime: '00:00:00',    duration:'00:00:00',  })  const audioRecorderPlayer = new AudioRecorderPlayer();  const meteringEnabled = false;   const SetRecording = () => {    onStartRecord();  };  const SetPauseRecording = () => {    onStopRecord();  };  const SetStartPlaying = () => {    onStartPlay();  };  const onStartRecord =  async() => {    if (Platform.OS === 'android') {      try {        const granted = await PermissionsAndroid.request(          PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,          {            title: 'Permissions for write access',            message: 'Give permission to your storage to write a file',            buttonPositive: 'ok',          },        );        if (granted === PermissionsAndroid.RESULTS.GRANTED) {          console.log('You can use the storage');        } else {          console.log('permission denied');          return;        }      } catch (err) {        console.warn(err);        return;      }    }    if (Platform.OS === 'android') {      try {        const granted = await PermissionsAndroid.request(          PermissionsAndroid.PERMISSIONS.RECORD_AUDIO,          {            title: 'Permissions for write access',            message: 'Give permission to your storage to write a file',            buttonPositive: 'ok',          },        );        if (granted === PermissionsAndroid.RESULTS.GRANTED) {          console.log('You can use the camera');        } else {          console.log('permission denied');          return;        }      } catch (err) {        console.warn(err);        return;      }    }    const path = Platform.select({      ios: 'file:////XXXXXXsomepathname/audio/helloworld.m4a',      android: 'file:////XXXXXXsomepathname/audio/helloworld.m4a',    });    const audioSet: AudioSet = {      AudioEncoderAndroid: AudioEncoderAndroidType.AAC,      AudioSourceAndroid: AudioSourceAndroidType.MIC,      AVEncoderAudioQualityKeyIOS: AVEncoderAudioQualityIOSType.high,      AVNumberOfChannelsKeyIOS: 2,      AVFormatIDKeyIOS: AVEncodingOption.aac,    };    console.log('audioSet', audioSet);    const uri = await audioRecorderPlayer.startRecorder(path, audioSet);    audioRecorderPlayer.addRecordBackListener((e: any) => {      setAudio({...audio,        recordSecs: e.current_position,        recordTime: audioRecorderPlayer.mmssss(          Math.floor(e.current_position),        ),      });      return;    });    console.log(`uri: ${uri}`);  };  const onStopRecord =  async() => {    const result = await audioRecorderPlayer.stopRecorder();    audioRecorderPlayer.removeRecordBackListener();    setAudio({...audio,      recordSecs: 0,    });    console.log(`this is the stop result: ${result}`);  };  const onStartPlay = async () => {    console.log('onStartPlay');    const path = Platform.select({      ios: 'file:////XXXXXXsomepathname/audio/helloworld.m4a',      android: 'file:////XXXXXXsomepathname/audio/helloworld.m4a',    });    const msg = await audioRecorderPlayer.startPlayer(path);    audioRecorderPlayer.setVolume(1.0);    console.log(msg);    audioRecorderPlayer.addPlayBackListener((e: any) => {      if (e.current_position === e.duration) {        console.log('finished');        audioRecorderPlayer.stopPlayer();      }      setAudio({...audio,        currentPositionSec: e.current_position,        currentDurationSec: e.duration,        playTime: audioRecorderPlayer.mmssss(          Math.floor(e.current_position),        ),        duration: audioRecorderPlayer.mmssss(Math.floor(e.duration)),      });      return    });  };

all the console.log is working, but I am not sure why it seems can't record the sound, I need to use the local path as I have more than one audio file need to be recorded.

Platform specific import component in react native with typescript

$
0
0

I am using react native with typescript. I have a component with the following structure

component    - component.ios.tsx    - component.android.tsx

Now I want to import the component. So, I am doing this:

import component from '../component/component';

But it says:

[ts] Cannot find module ../component/component

The location is correct. I need to add something to the tslint file to make it understand.

I also tried to do:

let component = require('../component/component');

This didn't give typescript error. But it gave a runtime error.

element type is invalid expected a string or a class/function but got undefined

Has anybody run into this issue?Thank you.

how to use navigation.replace in TypeScript?

$
0
0

I am trying to use this in my code:

const navigation = useNavigation();navigation.replace('AllFriends')

But I keep getting an error that:

Property 'replace' does not exist on type 'NavigationProp<Record<string, object | undefined>, string, NavigationState, {}, {}>'.

I also tried using this

const navigation =  useNavigation<StackNavigationProp<{route: {} }>>()navigation.replace('route');

as suggested here: https://github.com/react-navigation/react-navigation/issues/8256

but this gives me an error on replace that expected 2 arguments but got only 1...

I am using "@react-navigation/native": "^5.5.1",

VSCode TS error with React.forwardRef functional component

$
0
0

We are using JavaScript (not TypeScript) to write our component library, and we have checkJs: true in our project's jsconfig.json file.

All of our components are functional components (no class components). When a component requires a ref, we use React.forwardRef.

An example of a component for the sake of this question; not an actual component, but shows how we write our components:

import React from 'react';import { View } from 'react-native';import propTypes from './propTypes';export const Box = React.forwardRef(({ padding, children }, ref) => {  return (<View ref={ref} style={{ padding }}>      {children}</View>  );});Box.propTypes = propTypes;

However, this causes this "red squiggly line" error under the padding prop:

Property 'padding' does not exist on type '{ children?: ReactNode; }'.ts(2339)

And where the propTypes is assigned:

Type '{ padding: Requireable; }' has no properties in common with type 'WeakValidationMap<RefAttributes>'.ts(2559)

And when implementing this <Box> component, the red squiggly line appears under the component's name, and the error is:

Type '{ children: Element; }' has no properties in common with type 'IntrinsicAttributes & RefAttributes'.ts(2559)

The code itself is valid, and changing checkJs to false resolves this, but we want to keep checkJstrue.

What exactly are we doing wrong?


Type a property/variable that accepts the ref of a component?

$
0
0

I want to type this.engine property with GameEnginesomething like, engine: GameEngine;and but it causes error Property 'stop' does not exist on type 'GameEngine'when using a GameEnginestop() method like below

Is this even possible? Or does it make sense?

export default class Game extends React.PureComponent {  engine: GameEngine;  // engine: any; // this one works ofcourse  //...  pause() {    this.engine.stop()  }  render() {    return (<GameEngine        ref={(ref) => { this.engine = ref; }}      />    )  }}

The value can be obtained in the constructor function, but TypeError: Cannot read property'xxx' of undefined is output in the render function

$
0
0

In console.log (data ["users"] ["userId"] ["points"]) in getData () of the code below, 20 is output.

But in render ()<Text> {JSON.stringify (this.state.users.userId.points)} </ Text>When you run

TypeError: Cannot read property'points' of undefinedError is output.

How do I {JSON.stringify (this.state.users.userId.points)} </ Text>Can it be output as 20?

import React from 'react';import { Text, View, Button, StyleSheet, TouchableHighlight, FlatList} from 'react-native';import { FloatingAction } from "react-native-floating-action";import Icon from 'react-native-vector-icons/FontAwesome5';import * as firebase from 'firebase';import 'firebase/firestore';import env from '../../env.json';interface Props {  navigation: any;  route:any;  authorId:string;  postId:string;  userId:string;  win:string;  wni:string;  ideas:any;  }  interface State {    actions:{      text:string,      icon:JSX.Element,      name:string,      position:number    }[],    data:any,    points:number    users:any  }  const firebaseConfig = {    apiKey: env.apiKey,    authDomain: env.authDomain,    databaseURL: env.databaseURL,    projectId: env.projectId,    storageBucket: env.storageBucket,    messagingSenderId: env.messagingSenderId,    appId: env.appId,    measurementId: env.measurementId  };  if (firebase.apps.length === 0) {    firebase.initializeApp(firebaseConfig);  }  const db = firebase.firestore();  export class Rank extends React.Component<Props,State> {      constructor(props){          super(props)          this.state = {            actions:[              {                text: "Write down features",                icon: <Icon name="list" size={20}/>,                name: "feature",                position: 2              },              {                text: "Post your idea",                icon: <Icon name="lightbulb" size={20}/>,                name: "idea",                position: 1              }            ],            data:{},            points:0,            users:{}          }          this.getData()      }      async getData(){        let firestoreData = await db.collection("posts").doc(this.props.route.params.postId).get()        let data = firestoreData.data()        this.setState({          data:data,          users:data["users"]        })        console.log(data["users"]["userId"]["points"])      }      render(){        return (<View            style={styles.backgroundImage}><Text>{JSON.stringify(this.state.users.userId.points)}</Text></View>        )      }  }  const styles = StyleSheet.create({    backgroundImage: {        ...StyleSheet.absoluteFillObject,      },  })

Visual Studio Code:[js] types can only be used in a .ts file

$
0
0

Is it possible to use .js files in a typescript project in vs code? I have clone a react-native project from a github repository and opened it in visual studio code. When I add a tsconfig.json in order to start using typescript,I get a long list of errors. For example here is a drawer.js file (with es6 features):

enter image description here

Here is my tsconfig.json file (If I remove this file then every thing works fine, no error reported) :

enter image description here

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

$
0
0

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

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

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

My state variables and toggleExpansion function look like this:

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

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

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

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

Type 'string' is not assignable to type 'ImageSourcePropType'

$
0
0

BackgroundI'm trying to use a SVG component which has the property xlinkHref within an Image tag. The file was a plain SVG but I turned it into a React Native Component (TSX) using https://react-svgr.com/playground/?native=true. I've used very simple SVG icons before with the same method but none had the xlinkHref property.

Problem

The component at some point has an Image tag within it which goes like this: xlinkHref="data:image/png;base64,, however, straight after that it has about 474 lines of encripted information, or at least that is what I believe it is. As an example, this is the first half of the first line: iVBORw0KGgoAAAANSUhEUgAAAeUAAAJwCAYAAAC3c3kPAAAAAXNSR0IArs4c6QAAQABJREFUeAH. The xlinkHreftag is automatically highlighted as incorrect by VS Code and I get the error mentioned in the title:

Type 'string' is not assignable to type 'ImageSourcePropType'.

And below that the error message mentions that:

The expected type comes from property 'xlinkHref' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes<Component<ImageProps, any, any>> & Readonly & Readonly<...>'

I am not much of an expert programmer and can't understand what the error is trying to tell me, so if anyone would be as kind to explain, it'd mean a lot.

Question

Is it possible to use SVG components which have this kind of property and assigned value in React Native or is it simply not compatible? How can I go about solving it? Is this a known issue or have I just ran into a new roadblock? I couldn't find anything on the internet regarding this specific issue.

Thanks a lot in advance!

Pattern 'components/*/*' can have at most one '*' character

$
0
0

I am working on a React Native application with Expo, and I am using some template components from 3rd party.In my src directory, I have an "app" folder that holds my components to use.This is the app folder structure

And this is the whole folder structure

Almost every component is also structured in this way:Example of Button component

My tsconfig.json file is giving me problems, since I needed to change some paths as well:

{"compilerOptions": {"allowSyntheticDefaultImports": true,"jsx": "react-native","lib": ["dom", "esnext"],"moduleResolution": "node","noEmit": true,"skipLibCheck": true,"resolveJsonModule": true,"strict": true,"noImplicitAny": false,"baseUrl": "./","paths": {"components/*": ["./app/components"],"components/*/*": ["./app/components/*/index"],"services/*": ["./app/services"],"app/*": ["./app"],"navigation/*": ["./app/navigation"],"theme/*": ["./app/theme/*"]        }    }}

And it's complaining about that

Pattern 'components/*/*' can have at most one '*' character.

When I try to import a Button component into my page Register.tsx, this is what React native is complaining about:

Unable to resolve "components/atoms/text" from "app/components/atoms/button/index.js"

I am trying every solution to fix this but it doesn't work. I tried to manually change every import but this is not an option that could work, is extremely time consuming and it won't make any sense.

Any suggestion to fix this issue?

Reset current display index to first element in Pnp Carousel

$
0
0

I am using Pnp-SFX Carousel control in my react app.Here I am displaying Carousel like below:

<Carousel                            buttonsLocation={CarouselButtonsLocation.center}                            buttonsDisplay={CarouselButtonsDisplay.block}                            containerButtonsStyles={styles.carouselButtonsContainer}                            isInfinite={false}                            interval={null}                            startIndex={this.state.startIndex}                            prevButtonStyles={styles.preSlide}                            nextButtonStyles={styles.nextSlide}                            indicatorShape={CarouselIndicatorShape.circle}                            indicatorClassName={styles.customIndicator}                            element={this.state.allItems} // applying JSX element                            onMoveNextClicked={(index: number) => { }}                            onMovePrevClicked={(index: number) => { }}                                               />

I am setting the this.state.startIndex to '0'.I have dropdown also to filter to display to the specific element in the Carousel items on its change event. The event is triggering fine and filtering element in the Carousel by filtering in the this.state.allItems

But the Carousal is not displaying the element if we are not in the first element of the Carousel. But the filtered element is there in the 0th index element.

Kindly help on this.


how to generate signed apk in react native typescript project

$
0
0

i am generating signed apk in my react native typescript project on running " react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res" and "cd android ./gradlew bundleRelease" both command gives me error this

error The resource d:\sajid\reactNative\viewsTrend\index.js was not found. Run CLI with --verbose flag for more details.Error: The resource d:\sajid\reactNative\viewsTrend\index.js was not found.at d:\sajid\reactNative\viewsTrend\node_modules\metro\src\IncrementalBundler.js:157:26at gotStat (fs.js:1779:21)at FSReqCallback.oncomplete (fs.js:168:21)

i also tried with renaming index.tsx to index.js but didn't work.please signing apk with typescript project.

How to prevent FlatList re rendering when state changes

$
0
0

I got a very huge FlatList which renders 800 buttons with an Image and a Text. This list is inside a TabScreen, which is inside a home screen with another tabScreen which has a textinput. When I change the text inside this textInput, the setState triggers my flatlist which under the hood updates, renders again its tons of items and slows everything. How can i avoid this?

Home Screen:

export default function HomeScreen(props: any) {  const Tab = createBottomTabNavigator();  return (<View style={styles.home__container}><HeaderButton navigation={props.navigation} /><Tab.Navigator        screenOptions={({ route }) => ({          tabBarIcon: ({ focused, color, size }) => {            let iconName: string = "";            if (route.name === "Search") {              iconName = "ios-search";            } else if (route.name === "List") {              iconName = focused ? "ios-list-box" : "ios-list";            }            return <Ionicons name={iconName} size={size} color={color} />;          },        })}        tabBarOptions={{          activeTintColor: "#ffcb05",          inactiveTintColor: "#ffffff",          style: { backgroundColor: "#2a75bb" },        }}><Tab.Screen name="Search" component={TabSearchScreen} /><Tab.Screen  name="List" component={TabListScreen} /></Tab.Navigator><PokemonSavedContainer navigation={props.navigation} /></View>  );}

FlatList Tab (TabListScreen) :

const TabListScreen = () => {  const flatListRef = useRef<FlatList<{ name: string }>>(null);  const scrollList = (index: number) => {    if (flatListRef.current)      flatListRef.current.scrollToIndex({ index: index });  };  const keyExtractor = (item: any) => `key-${item.name}`;  const renderItem = (item: any) => {    return (<MySwipeable pokeNumber={item.index + 1} pokeName={item.item.name} />    );  };  return (<View style={styles.pokedex__list}><FlatList        data={pokedex}        ref={flatListRef}        renderItem={renderItem}        keyExtractor={(item) => keyExtractor(item)}        style={styles.pokedex__list__pokemons}        onScrollToIndexFailed={() => alert("something went wrong")}        getItemLayout={(data, index) => ({          length: 100,          offset: 100 * index,          index,        })}      /><View style={{ flexDirection: "column", marginTop: 20 }}><SmallButton onPress={() => scrollList(0)} title="Kanto" /><SmallButton onPress={() => scrollList(151)} title="Jhoto" /><SmallButton onPress={() => scrollList(251)} title="Hoenn" /><SmallButton onPress={() => scrollList(386)} title="Sinnoh" /><SmallButton onPress={() => scrollList(494)} title="Unova" /><SmallButton onPress={() => scrollList(649)} title="Kalos" /><SmallButton onPress={() => scrollList(721)} title="Alola" /><SmallButton onPress={() => scrollList(809)} title="Galar" /></View></View>  );};export default TabListScreen;

textInput Screen (TabSearch Screen):

export default function TabSearchScreen() {  const pokemonState = useSelector((state: RootStore) => state.pokemon);  return (<View style={styles.home__container}><Searchbar />      {pokemonState.pokemon && <PokeContainer />}</View>  );}

Search Component

export default function Searchbar() {  const dispatch = useDispatch();  const handleSubmit = () => {    dispatch(GetPokemon(pokemonName));  };  const [pokemonName, setPokemonName] = useState("");  return (<View style={styles.home__search}><TextInput        style={styles.home__search__textInput}        onChangeText={(value) => setPokemonName(value)}        value={pokemonName}      /><PokeBallButton title="search" onPress={handleSubmit} /></View>  );}

FlatList Item (called Myswipeable because i want to give it swipe functionality)

export interface MySwipeProps {  children?: React.ReactNode;  props?: any;  pokeName: string;  pokeNumber: number;}const MySwipeable: React.FC<MySwipeProps> = ({  children,  pokeName,  pokeNumber,  ...props}) => {  console.log("pokemon");  const renderLeftActions = () => {    return <Animated.View></Animated.View>;  };  return (<Swipeable renderLeftActions={renderLeftActions}><View style={styles.button__list__container}><Image          source={{            uri: `https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${pokeNumber}.png`,          }}          style={styles.pokemonTiny}        /><Text style={styles.button__list__text}>{pokeName}</Text></View></Swipeable>  );};export default MySwipeable;

Typescript issue in Styled component Button ( React-Native )

$
0
0

this code :

import React from 'react';import styled from 'styled-components/native';const Button = styled.Button`  color: palevioletred;`;interface Props {}interface State {}export default class App extends React.Component<Props, State> {  render() {    return <Button> Test btn</Button>;  }}

throws this error :

No overload matches this call.Overload 1 of 2, '(props: Pick<Pick<ButtonProps & RefAttributes, "testID" | "accessibilityLabel" | "onPress" | "ref" | "title" | "color" | "key" | "disabled"> & Partial<...>, "testID" | ... 6 more ... | "disabled"> & { ...; } & { ...; } & { ...; }): ReactElement<...>', gave the following error.Type '{ children: string; }' is missing the following properties from type 'Pick<Pick<ButtonProps & RefAttributes, "testID" | "accessibilityLabel" | "onPress" | "ref" | "title" | "color" | "key" | "disabled"> & Partial<...>, "testID" | ... 6 more ... | "disabled">': onPress, titleOverload 2 of 2, '(props: StyledComponentPropsWithAs<typeof Button, DefaultTheme, {}, never>): ReactElement<StyledComponentPropsWithAs<typeof Button, DefaultTheme, {}, never>, string | ... 1 more ... | (new (props: any) => Component<...>)>', gave the following error.Type '{ children: string; }' is missing the following properties from type 'Pick<Pick<ButtonProps & RefAttributes, "testID" | "accessibilityLabel" | "onPress" | "ref" | "title" | "color" | "key" | "disabled"> & Partial<...>, "testID" | ... 6 more ...

i HAVE installed @types/styled-componentswhy this occurs?

Ionic React - how to hide the Ion-Split-Pane when in the login and registration page

$
0
0

The main issue I am having is I don't know how to hide the IonSplitPane when I am not logged into the application. If anyone knows a solution to this issue it would be appreciated as the only answers online are done through Ionic Angular and not React with TypeScript.

Below is the app.tsx where the is placed.

const RoutingSystem: React.FC = () => {  return (<IonReactRouter><IonSplitPane className="n" contentId="main"><SideMenu /><IonRouterOutlet id="main"><Route path="/" component={Home} exact /><Route path="/login" component={Login} exact /><Route path="/register" component={Register} exact /><Route path="/filter" exact><Filter /></Route><Route path="/tabs" exact><TabsMenu /></Route><Redirect to="/tabs" /></IonRouterOutlet></IonSplitPane></IonReactRouter>  );};const App: React.FC = () => {  const [busy, setBusy] = useState(true);  const dispatch = useDispatch();  useEffect(() => {    getCurrentUser().then((user: any) => {      console.log(user);      if (user) {        dispatch(setUserState(user.email));        window.history.replaceState({}, "/", "/tabs/newsfeed");      } else {        window.history.replaceState({}, "", "/");      }      setBusy(false);    });  }, []);  return (<IonApp>      {busy ? (<IonSpinner className="spinnerCenter" name="bubbles" color="primary" />      ) : (<RoutingSystem />      )}</IonApp>  );};export default App;

Here is the sideMenu component for the applcation.

import React from "react";import {  IonMenu,  IonHeader,  IonToolbar,  IonTitle,  IonContent,  IonItem,  IonIcon,  IonLabel,  IonToggle,} from "@ionic/react";import { moon, logoGithub } from "ionicons/icons";const SideMenu: React.FC = () => {  return (<IonMenu contentId="main"><IonHeader><IonToolbar><IonTitle>Opportunity</IonTitle></IonToolbar></IonHeader><IonContent><IonItem><IonIcon slot="start" icon={moon} /><IonLabel>Dark Mode</IonLabel><IonToggle            color="primary"            slot="end"            name="darkMode"            onIonChange={toggleDarkModeHandler}          /></IonItem><IonItem          button          href="https://github.com/ionic-team/ionic"          routerDirection="none"><IonIcon slot="start" icon={logoGithub} /><IonLabel>Github Repo</IonLabel></IonItem></IonContent></IonMenu>  );};const toggleDarkModeHandler = () => {  document.body.classList.toggle("dark");};export default SideMenu;

Here is the login.tsx page I also have a home.tsx and registrationpage which are similar which I can show if needed.

import { Link, useHistory } from "react-router-dom";import { loginUser } from "../firebaseSetup";import { toast } from "../toast";import { setUserState } from "../redux/actions";import { useDispatch } from "react-redux";const Login: React.FC = () => {  const [busy, setBusy] = useState<boolean>(false);  const history = useHistory();  const dispatch = useDispatch();  const [username, setUsername] = useState("");  const [password, setPassword] = useState("");  async function login() {    setBusy(true);    const res: any = await loginUser(username, password);    if (res) {      console.log(res);      dispatch(setUserState(res.user.email));      history.replace("/tabs/newsfeed");      toast("You have logged in!");    }    setBusy(false);  }  return (<IonPage><IonHeader><IonToolbar><IonButtons slot="start"><IonBackButton defaultHref="/" /></IonButtons><IonTitle>Login</IonTitle></IonToolbar></IonHeader><IonLoading message="Please wait.." duration={0} isOpen={busy} /><IonContent className="ion-padding"><IonInput          placeholder="Email?"          onIonChange={(e: any) => setUsername(e.target.value)}        /><IonInput          type="password"          placeholder="Password?"          onIonChange={(e: any) => setPassword(e.target.value)}        /><IonButton onClick={login}>Login</IonButton><p>          New to Opportunity? <Link to="/register">Register</Link></p></IonContent></IonPage>  );};export default Login;

How to setState with an Array and object in Typescript?

$
0
0

This is how I declare a state

const [input, setInput] = React.useState('')const [goals, setGoals] = React.useState<string[]>([])

and this is my error code:

const addHandler = () => {    setGoals((curGoals) => [...curGoals, { key: Math.random().toString(), value:input}])}

This is a typescript hint:

Argument of type '(curGoals: string[]) => (string | { key: string; value: string; })[]' is not assignable to parameter of type 'SetStateAction<string[]>'.Type '(curGoals: string[]) => (string | { key: string; value: string; })[]' is not assignable to type '(prevState: string[]) => string[]'.Type '(string | { key: string; value: string; })[]' is not assignable to type 'string[]'.Type 'string | { key: string; value: string; }' is not assignable to type 'string'.Type '{ key: string; value: string; }' is not assignable to type 'string'.ts(2345)

I still don't understand why my code still outputs this error. I did use a string type of array with useState.

How can I resolve this error?

Viewing all 6213 articles
Browse latest View live


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