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

Filtering objects based on conditions using Ramda

$
0
0

I want to filter out below data using Ramda. The desired result is to show the properties where usage === 'Defining'.

const data = [{"attributes":  [    {"usage": "Descriptive"},    {"usage": "Defining"}  ]}]

So far this is what i have done and it's not filtering out data and returning the whole object.

R.filter( R.compose(     R.any(R.propEq('usage', 'Defining')),     R.prop('attributes')  ))(data)

Below is the desired result that i want to acheive:

[{"attributes":  [    {"usage": "Defining"}  ]}]

React Native Dialog inside MapView

$
0
0

I am trying to put a Dialog component inside a MapView but this one is only showed when the map unmounts (too strange). I am using react-native-popup-dialog, but I have also tried to use other libraries and having the same problem. I don't know what I am doing wrong, because if in the code I replace this Dialog component with a Text, the text is correctly shown.

Map.js

<View style={[styles.container, { backgroundColor: colors.white }]}><MapView    ref={mapRef}    key={key}    mapType="standard"    rotateEnabled={false}    showsUserLocation={showsUserLocation}    renderToHardwareTextureAndroid={true}    loadingEnabled={true}    loadingIndicatorColor={colors.primary}    initialRegion={initialRegion}    provider={PROVIDER_GOOGLE}    customMapStyle={mapStyle}    style={styles.map}>    {marker && marker.coordinate && (<MapView.Marker        key={marker.id}        coordinate={marker.coordinate}        title={marker.title}        pinColor={colors.primary}      />    )}</MapView><AnimatedDialog visible title="Hello" text="Example"/> {/*MY CUSTOM COMPONENT*/}</View>

AnimatedDialog.js

<Dialog  useNativeDriver={true}  visible={visible}  rounded  dialogAnimation={    new SlideAnimation({      slideFrom: "bottom",    })  }  dialogTitle={<DialogTitle title={title} />}  footer={<DialogFooter><DialogButton        text="CANCEL"        onPress={() => {}}      /><DialogButton text="OK" onPress={() => {}} /></DialogFooter>  }><DialogContent><Text>{text}</Text></DialogContent></Dialog>

Can't remove a growing margin at bottom of screen- video keeps getting pushed up (React native Tiktok video app)

$
0
0

I'm working on a tiktok-like video app, and when I scroll down, the video is supposed to adjust and fit the full screen perfectly, but the video isn't adjusting properly to fit the full screen, it has a growing margin at the bottom. For each video I scroll down, the margin at the bottom gets bigger. I don't want any margin at the bottom. I have recorded a short video of the problem so you can see what I'm talking about (at the end is the best demo) https://streamable.com/tihyt4

(Here is a second link incase that doesn't work: https://imgur.com/a/FNltUE8 sorry its so large, just scroll to see the bottom of it)

When I press pause though, the video(the entire container? likes and all) re-adjusts to fit the screen correctly, why isn't it doing this in the beginning when I scroll down to the next video?

Below I have attached all the code that I think might be related to this problem

This is my Home.tsx:

import React from "react";import { Text, Animated, ScrollView, KeyboardAvoidingView } from "react-native";import { HomeStore } from "../../Stores";import { hoc, ps } from "../../Modules";import { TypedComponent } from "../../Components";import { homeStyle } from "./styles";import { VideoList } from "./VideoList";import { HomeTab } from "./HomeTab";import { Comments } from "./Comments";@hoc("home")export class Home extends TypedComponent<{ home?: HomeStore }> {  render() {    const { home, lang } = this.props;    const str = lang.str.home;    return (<KeyboardAvoidingView style={ps.container} behavior="padding" enabled><Animated.ScrollView          horizontal          pagingEnabled          bounces={false}          directionalLockEnabled          style={homeStyle.hSwiperContainer}          contentContainerStyle={homeStyle.hScrollContent}          onScroll={home.onScrollEvent}><VideoList            videoList={home.followList}            tabFocus={home.selectedTab === 0}            onFocusVideoChange={home.onFocusVideoChange}          /><VideoList            videoList={home.recommendList}            tabFocus={home.selectedTab === 1}            onFocusVideoChange={home.onFocusVideoChange}          /><ScrollView            horizontal={false}            style={ps.container}            contentContainerStyle={[ps.container, ps.center]}><Text>{lang.str.home.authorInfo}</Text></ScrollView><HomeTab /></Animated.ScrollView><Comments video={home.focusVideo} /></KeyboardAvoidingView>    );  }}export default Home;//lets hope this works

HomeStore: where I keep my onHScroll Action:

import { observable, action } from "mobx";import { VideoInfo } from "./VideoInfo";import { Animated, Dimensions } from "react-native";import { mockVideoList1 } from "./Mock";const screenWidth = Dimensions.get("window").width;const screenHeight = Dimensions.get("window").height;export class HomeStore {  @observable followList: VideoInfo[] = mockVideoList1();  @observable recommendList: VideoInfo[] = mockVideoList1();  @observable focusVideo: VideoInfo = this.followList[0];  @observable selectedTab: number = 0;  @action onHScroll = (e: any) => {    this.selectedTab = Math.floor(      (e.nativeEvent.contentOffset.x / e.nativeEvent.contentSize.width) * 3    );  };  private contentOffsetX = new Animated.Value(0);  onScrollEvent = Animated.event([{ nativeEvent: { contentOffset: { x: this.contentOffsetX } } }], {    useNativeDriver: true,    listener: this.onHScroll,  });  @action onFocusVideoChange = (video: VideoInfo) => {    this.focusVideo = video;  };  navStyle = {    position: "absolute",    left: 0,    width: "33.33%",    top: 0,    paddingHorizontal: 30,    transform: [      {        translateX: this.contentOffsetX.interpolate({          inputRange: [-1, 0, screenWidth, screenWidth + 1],          outputRange: [0, 0, screenWidth, screenWidth],        }),      },    ],  };  indicatorStyle = {    position: "absolute",    left: 0,    width: 36,    bottom: 0,    height: 3,    backgroundColor: "white",    transform: [      {        translateX: this.contentOffsetX.interpolate({          inputRange: [-1, 0, screenWidth, screenWidth + 1],          //outputRange: [0, 0, 52, 52],          outputRange: [10, 10, 85, 85],        }),      },    ],  };  private commentsY = new Animated.Value(screenHeight - 100);  commentsStyle = {    position: "absolute",    top: 100,    left: 0,    right: 0,    bottom: 0,    borderRadius: 10,    padding: 20,    backgroundColor: "white",    transform: [{ translateY: this.commentsY }],  };  onProfileOpen = () => {    //TODO: Add actual profile openings    Animated.timing(this.commentsY, {      toValue: 0,      duration: 300,      useNativeDriver: true,    }).start();  };  onCommentOpen = () => {    Animated.timing(this.commentsY, {      toValue: 0,      duration: 300,      useNativeDriver: true,    }).start();  };  onCommentClose = () => {    Animated.timing(this.commentsY, {      duration: 300,      toValue: screenHeight - 100,      useNativeDriver: true,    }).start();  };}

This is the code I'm using for the swiping(VideoList.tsx):

import React from "react";import Swiper from "react-native-swiper";import { VideoInfo } from "../../Stores/VideoInfo";import { TVideo } from "./TVideo";export class VideoList extends React.Component<{  videoList: VideoInfo[];  tabFocus: boolean;  onFocusVideoChange: (video: VideoInfo) => any;}> {  render() {    return (<Swiper        horizontal={false}        loop={false}        bounces={false}        showsPagination={false}        onIndexChanged={index => {          this.props.videoList.forEach((video, idx) => {            if (video.focus) video.onBlur();            if (index === idx) {              this.props.onFocusVideoChange(video);              video.onFocus();            }          });        }}>        {this.props.videoList.map((video, idx) => {          return <TVideo video={video} key={video.id} tabFocus={this.props.tabFocus} />;        })}</Swiper>    );  }  componentDidMount() {    if (this.props.videoList.length <= 0) return;    this.props.videoList[0].onFocus();    this.props.tabFocus && this.props.onFocusVideoChange(this.props.videoList[0]);  }}

This is the code for a Video (TVideo.tsx):

import React, { useState } from "react";import { Text, StyleSheet, View, Image, Dimensions } from "react-native";import { ps, hoc } from "../../Modules";import { VideoInfo } from "../../Stores/VideoInfo";import Video from "react-native-video";import { TouchableOpacity } from "react-native";import { homeStyle } from "./styles";import { TypedComponent } from "../../Components";import { Comments } from "./Comments";import { HomeStore } from "../../Stores";import ViewPager  from "@react-native-community/viewpager";import styled from 'styled-components/native';import Info from "./Info";const Count = styled.Text`    color: #fff;    font-size: 12px;  letter-spacing: -0.1px;  textAlign: center;`const Center = styled.View`    flex: 1;    flex-direction: row;`@hoc("home")export class TVideo extends TypedComponent<{  video: VideoInfo;  tabFocus: boolean;  home?: HomeStore;}> {  render() {    const { video, tabFocus, lang, home } = this.props;    const str = lang.str.home;    return (      // <View style={ps.container}><View style={ps.container}><Video          repeat          controls={false}          resizeMode="cover"          style={[ps.container]}          onReadyForDisplay={video.onReady}          paused={!(tabFocus && video.ready && video.focus && !video.paused)}          source={{            uri: this.props.video.uri,          }}        /><TouchableOpacity style={[StyleSheet.absoluteFill, ps.center]} onPress={video.onPause}>          {video.paused && (<Image style={homeStyle.playButton} source={require("../../../Assets/play.png")} />          )}</TouchableOpacity>        {/* <Center> */}<View style={homeStyle.totalContainer}><Info></Info ><View style={homeStyle.fabContainer}>< TouchableOpacity onPress={home.onProfileOpen}><Image resizeMode='cover' style={homeStyle.fabButton} source={require("../../../Assets/avatar.png")} /></TouchableOpacity><View style={{              width: 36,              height: 18,              justifyContent: "center",              borderRadius: 36 / 2,              backgroundColor: 'pink',            }}><Text style={{              alignSelf: 'center',              fontWeight: 'bold',              color: 'white',              fontSize: 11,            }}>♀18</Text></View><Count></Count><Count></Count><Count></Count><TouchableOpacity onPress={home.onProfileOpen}><Image resizeMode='contain' style={homeStyle.fabButton} source={require("../../../Assets/icons/like.png")} /><Count>{200}</Count><Count></Count><Count></Count></TouchableOpacity><TouchableOpacity onPress={home.onCommentOpen}><Image resizeMode='contain' style={homeStyle.fabButton} source={require("../../../Assets/icons/comment.png")} /><Count>{1000}</Count><Count></Count><Count></Count></TouchableOpacity><TouchableOpacity><Image resizeMode='contain' style={homeStyle.fabButton} source={require("../../../Assets/location.png")} /><Count>{"2mi"}</Count><Count></Count><Count></Count></TouchableOpacity></View></View>        {/* </Center> */}        {/* {tabFocus && video.focus && <Comments video={video} />} */}</View>    );  }}

This is styles.tsx (the 'homeStyle' that TVideo uses):

import { StyleSheet } from "react-native";export const homeStyle = StyleSheet.create({  hSwiperContainer: {    flex: 1,  },  hScrollContent: {    width: "300%",    height: "100%",    flexDirection: "row",  },  safeNav: {    flexDirection: "row",    justifyContent: "space-between",  },  tabContainer: {    minWidth: 80,    minHeight: 30,    flexDirection: "row",    justifyContent: "space-between",    alignItems: "center",  },  tabButton: {    fontSize: 18,    fontWeight: "bold",    color: "#C0C4C2",  },  descContainer: {    position: "absolute",    top: 0,    left: 15,    bottom: 10,    justifyContent: "flex-end",    //justifyContent: "center",    //alignItems: "center",    //flexDirection: "row",    flex: 1,  },  totalContainer:{    position: "absolute",    justifyContent:"space-between",    //top:0,    bottom:10,    flexDirection: "row",    flex: 1,  },  fabContainer: {    position: "absolute",    top: 0,    right: 15,    bottom: 50,    justifyContent: "flex-end",    //justifyContent: "center",    alignItems: "center",    //flexDirection: "row",    flex: 1,  },  author: {    fontSize: 16,    color: "gray",  },  comment: {    fontSize: 14,  },  commentClose: {},  commentHeader: {    flexDirection: "row",    justifyContent: "space-between",  },  location: {    flexDirection: "row",    alignItems: "center",  },  locationIcon: {    width: 30,    height: 30,  },  locationText: {    marginLeft: 15,    color: "lightgray",  },  postContainer: {    minHeight: 48,    flexDirection: "row",    alignItems: "center",    borderTopWidth: 1,    borderColor: "lightgray",  },  input: {    flex: 1,  },  fabButton: {    width: 48,    height: 48,    // padding: 30,  },  playButton: {    width: 100,    height: 100,  },});

And the ps from /Modules which most of the above files use:

export const ps = StyleSheet.create({  container: {    flex: 1,  },  center: {    justifyContent: "center",    alignItems: "center",  },});

Can somebody help me get rid of the bottom margin of the containers when scrolling down? If any other code is needed just tell me, and I'll edit this post to add it. If you have an idea, I'll try it out and tell you the results

Type annotations can only be used in TypeScript files. ts(8010)

$
0
0

I'm following a tutorial (link to tutorial below) on setting up an IAP (In-App-Purchase) for a react native app. While writing the code, vs code is warning me that "Type Annotations can only be used in TypeScript files", this warned under the "purchase: InAppPurchase | SubscriptionPurchase" and "error: PurchaseError" part of the code. When looking into this, the most popular solution I could find (on Stack Overflow or elswhere) was to simply disable the 'TypeScript and JavaScript Language Features'.

I don't feel like that solves the problem, but I'm not sure. Would disabling this solve the problem and let my app run as expected? Or is there is another way to include this typescript syntax in my javascript file?

    useEffect(() => {    purchaseUpdateSubscription = RNIap.purchaseUpdatedListener(        async (purchase: InAppPurchase | SubscriptionPurchase) => {            const receipt = purchase.transactionReceipt;            if (receipt) {                try {                    if (Platform.os === 'ios') {                        RNIap.finishTransactionIOS(purchase.transactionReceipt)                    }                    await RNIap.finishTransaction(purchase)                    await processNewPurchase(purchase)                } catch (ackErr) {                    console.log('ackErr', ackErr)                }            }        }    );    purchaseErrorSubscription = RNIap.purchaseErrorListener(        (error: PurchaseError) => {            console.log('purchaseErrorListener', error)        }    );    return (() => {        if (purchaseUpdateSubscription) {            purchaseUpdateSubscription.remove()            purchaseUpdateSubscription = null;        }        if (purchaseErrorSubscription) {            purchaseErrorSubscription.remove()            purchaseUpdateSubscription = null;        }    })}, [])

link to tutorial: https://medium.com/@rossbulat/react-native-subscriptions-with-in-app-purchases-setup-fdaf3863e07f

typescript in a js file?

$
0
0

I'm attempting to follow the react-native-iap documentation, but keep running into the issue of "Type Annotations can only be used in TypeScript files".

When I look at their example (https://github.com/dooboolab/react-native-iap/blob/master/IapExample/App.js) the file is still a js file, and they use the same type annotation that I've used in my project:

async (purchase: InAppPurchase | SubscriptionPurchase)

Any idea how they were able to use type annotation in their js file? Or am I too focused on the error message, and simply need to disable 'TypeScript and JavaScript Language Features'?

React useState hook gets typed incorrectly

$
0
0

When I try to use useState hook without default value it get's typed incorrectly. It doesn't include undefined in possible types. For example in component bellow:

type Color = 'blue' | 'yellow' | 'red';const MyComponent: React.FC = () => {  const [color, setColor] = useState<Color>();  color.toLocaleLowerCase();  return null;};

The color is typed as Color and therefore color.toLocaleLowerCase() won't raise any typescript error, even though in reality the color can also be undefined (which of course, would cause runtime error).

I even tried specifying the undefined explicitly as possible type: const [color, setColor] = useState<Color | undefined>(); but color is still typed just as Color.

I am almost sure that this used to work. Did anyone else ran into similar issue?

Some dependencies:

"react": "16.9.0","expo": "^37.0.0","react-native": "https://github.com/expo/react-native/archive/sdk-37.0.1.tar.gz","@babel/preset-typescript": "^7.8.3","@typescript-eslint/parser": "^2.28.0","@typescript-eslint/eslint-plugin": "^2.28.0","typescript": "^3.8.3",

My tsconfig.json:

{"compilerOptions": {"allowJs": true,"allowSyntheticDefaultImports": true,"jsx": "react-native","lib": ["dom", "esnext"],"moduleResolution": "node","noEmit": true,"skipLibCheck": true,"noImplicitAny": true,"resolveJsonModule": true,"esModuleInterop": true,"isolatedModules": false,"baseUrl": "./","sourceMap": true,  }}

extract object from array - typescript

$
0
0

I have a trip object that looks like this:

Array (1)0 {id: 1, vehicle: {freeSeats: 2, __typename: "Vehicle"}, startLocation: "{\"type\":\"Point\",\"coordinates\":[8.217462,53.13975]}", endLocation: "{\"type\":\"Point\",\"coordinates\":[8.258844,53.119525]}", timeOfDeparture: "2020-06-16T11:48:00.869Z", …}
type TripListProps = {  trips: any; //TODO FIX  //trips: Array<Trip>,  friendIds: Array<number>,};export const TripList: React.FunctionComponent<TripListProps> = ({ trips, friendIds }) => {  console.log('trips', trips);  if (trips.length > 0) {    return ( <View style={{ height: 500 }}><FlatList          data={trips}          horizontal={false}          scrollEnabled          renderItem={({ item }) => <TripContainer trip={item} friendIds={friendIds} />}          keyExtractor={(trip: any) => trip.id.toString()}        /></View>    )  } else {    return (<View style={styles.noTripsFound}><Text style={styles.text}>No trips found</Text></View>);  }};

It's original type is Array<Trip>. However, here I am passing it to another component TripContainer, which requires trip to be in this form:

trip: {  driver: {      firstName: string;      rating: number;      id: number;  };  timeOfDeparture: any;}

Because of this, if I change my TripListPropsfrom trips: any to trips: Array<Trip>, I get an error.

Is there any way I can extract only this part from the whole array object?

unable to scroll PanGestureHandler

$
0
0

I am using a Modal to open a PanGestureHandler (UserInfoContainer) for animation. The PanGestureHandler loads but the initial height expands to almost the full page and I cannot scroll it down using the white bar. How can I fix this?

export const UserInfoContainer: React.FC<PanGestureProps> = ({ firstName, rating, numberOfFriends }) => {  const dragY = useRef(new Animated.Value(0));  const onGestureEvent = Animated.event(    [{ nativeEvent: { translationY: dragY.current } }],    {      useNativeDriver: true,    },  );  const onHandleStateChange = (event: any) => {    if (event.nativeEvent.oldState === State.ACTIVE) {      dragY.current.extractOffset();    }  };  const animateInterpolation = dragY.current.interpolate({    inputRange: [-SCREEN_HEIGHT + SCREEN_HEIGHT / 4 + SCREEN_HEIGHT / 10, 0],    outputRange: [-SCREEN_HEIGHT + SCREEN_HEIGHT / 4 + SCREEN_HEIGHT / 10, 0],    extrapolate: 'clamp',  });  const animatedStyles = {    transform: [      {        translateY: animateInterpolation,      },    ],  };  const whitelistBarMarginInterpolation = dragY.current.interpolate({    inputRange: [-SCREEN_HEIGHT + SCREEN_HEIGHT / 3, 0],    outputRange: [0, moderateScale(150)],    extrapolate: 'clamp',  });  const whitelistBarStyles = {    transform: [      {        translateY: whitelistBarMarginInterpolation,      },    ],  };  return (<PanGestureHandler      onGestureEvent={onGestureEvent}      onHandlerStateChange={onHandleStateChange}><Animated.View        style={[          styles.container,          animatedStyles,          /* { transform: [{ translateY: dragY.current }] } */        ]}><SwipeBar /><View style={styles.introContainer}><Text style={styles.name}>            {firstName}</Text><Animated.View style={[styles.whitelistBar, whitelistBarStyles]}></Animated.View></Animated.View></PanGestureHandler>  );};

enter image description here

The white background is from the modal. The greyish one is the pan gesture handler.


decrease initial height on PanGestureHandler

$
0
0

Using a react-native Modal, I open a PanGestureHandler (UserInfoContainer) for animation.T he panhandler opens up when but the initial height covers almost the full screen. How can I reduce the height of the entire handler? This code is also used on another screen but the length /height is automatically different. How can I fix this?

export const UserInfoContainer: React.FC<PanGestureProps> = ({ firstName}) => {  const dragY = useRef(new Animated.Value(0));  const onGestureEvent = Animated.event(    [{ nativeEvent: { translationY: dragY.current } }],    {      useNativeDriver: true,    },  );  const onHandleStateChange = (event: any) => {    if (event.nativeEvent.oldState === State.ACTIVE) {      dragY.current.extractOffset();    }  };  const animateInterpolation = dragY.current.interpolate({    inputRange: [-SCREEN_HEIGHT + SCREEN_HEIGHT / 4 + SCREEN_HEIGHT / 10, 0],    outputRange: [-SCREEN_HEIGHT + SCREEN_HEIGHT / 4 + SCREEN_HEIGHT / 10, 0],    extrapolate: 'clamp',  });  const animatedStyles = {    transform: [      {        translateY: animateInterpolation,      },    ],  };  const whitelistBarMarginInterpolation = dragY.current.interpolate({    inputRange: [-SCREEN_HEIGHT + SCREEN_HEIGHT / 3, 0],    outputRange: [0, moderateScale(150)],    extrapolate: 'clamp',  });  const whitelistBarStyles = {    transform: [      {        translateY: whitelistBarMarginInterpolation,      },    ],  };  return (<PanGestureHandler      onGestureEvent={onGestureEvent}      onHandlerStateChange={onHandleStateChange}><Animated.View        style={[          styles.container,          animatedStyles,        ]}><SwipeBar /><View><Text>            {firstName}</Text><Animated.View style={[styles.whitelistBar, whitelistBarStyles]}></Animated.View></Animated.View></PanGestureHandler>  );};

typeError: (evaluating _this.currentObservable.query.refetch)

$
0
0

On my screen, I use delete buttons. Upon clicking the delete buttons, I run a graphql mutation and in order to get and render updated data, I call refetch every time. Similarly, whenever I enter the screen, I call refetch within useEffect. This process works fine.

However, every time I change anything minor in my code, for instance within UserDetails, which is a part of the ContactList, the app crashes and gives me this error:

TypeError: undefined is not an object (evaluating '_this.currentObservable.query.refetch')This error is located at:    in Whitelist (at SceneView.tsx:98)

When I reload the app, everything works fine. So I don't know what triggers this error initially. How can I fix this? Is it a problem in the code or refetch/apollo?

export const Whitelist: React.FunctionComponent = (props) => {  console.log('props in whitelist', props);  const navigation = useNavigation();useFocusEffect(  useCallback(() => {    refetch();  }, []));  const [deleteUserRelationMutation] = useDeleteUserRelationMutation({    onCompleted: () => {      refetch();      Alert.alert('Contact Deleted');    },    onError: _onDeleteUserRelationError,  });  const onDeleteContact = (relationId: number) => {    Alert.alert('Warning', 'Are You Sure You Want to Delete Contact?', [      {        text: 'Cancel',      },      {        text: 'Yes',        onPress: () => {          deleteUserRelationMutation({            variables: { id: relationId },          });        },      },    ]);  };  const { error, data, refetch } = useUsersQuery({    variables: {      where: { id: 1 },    },  });  return (<SafeAreaView style={styles.safeView}><Container style={styles.container}><Text onPress={() => navigation.navigate('Home')}>Zurück</Text><View></View><ContactList          data={data}          onDeleteContact={onDeleteContact}></ContactList></Container></SafeAreaView>  );};

put space between items in a row

$
0
0

Is there any way to style elements (from the ratings view) in such a way that there's automatically some space between them? I thought of printing text (white spaces) but that doesn't sound like an ideal solution. What else can I do?

<View style={styles.introContainer}><Text style={styles.name}>{firstName}</Text><View style={styles.ratings}><Icon name="user" size={moderateScale(20)} /><Icon name="star" size={moderateScale(13)} /><Text style={styles.rating}> {rating}</Text></View></View>

ss

  ratings: {    flexDirection: 'row',    //alignContent: 'center',    alignItems: 'baseline',  },  introContainer: {    alignItems: 'center',    paddingTop: 50,    width: '100%',  },

change color of full Modal

$
0
0

I'm using a react native modal. I am trying to use a backgroundColor to fill the whole modal. However, the color is only applied to the top. Why is this so?

How can I fix this and apply the color to the whole modal view?

return (<Modal visible={isUserVisible}><View style={styles.container}>      {/* <View> */}<View><TouchableOpacity            style={styles.cross}            onPress={() => setIsUserVisible(false)}><Thumbnail              source={{                uri:'https://cdn0.iconfinder.com/data/icons/very-basic-android-l-lollipop-icon-pack/24/close-512.png',              }}></Thumbnail></TouchableOpacity><Text>HELLOO</Text></View><View style={styles.searchLocationContainer}><UserInfoContainer            firstName={firstName}</UserInfoContainer></View></View></Modal>
export const styles = StyleSheet.create({  container: {    backgroundColor: '#323443',    //backgroundColor: 'red',  },  button: {    paddingTop: 0,  },  text: {    color: 'black',  },  cross: {    paddingTop: 50,    paddingLeft: 40,  },  searchLocationContainer: {    flex: 1,  },});

enter image description here

enter image description here

The greyish thing is from a pangesturehandler coming from UserInfoContainer.

draw a vertical line between 2 objects

$
0
0

Is it possible to draw a vertical line between 2 text objects? I looked into this but this is not exactly what I need:

https://reactjsexample.com/draw-a-line-between-two-elements-in-react/

enter image description here

<View style={styles.ridesFriends}><Text style={styles.numbers}>132    </Text><Text style={styles.numbers}>{numberOfFriends}</Text></View>
  ridesFriends: {    paddingTop: 70,    alignItems: 'center',    flexDirection: 'row',    justifyContent: 'space-evenly',    width: '100%',  },

TouchableOpacity overwriting other buttons

$
0
0

In my component, I was rendering a button for each Item. It was working. However, when I wrap all of it in a touchable TouchableOpacity, the button no longer works. Everything is the touchable opacity now. How can I still use the button?

          return (<TouchableOpacity onPress= {()=> console.log('Hello')}><View style={styles.item} key={item.id}><Thumbnail                style={styles.thumbnail}                source={{                  uri:'https://cdn4.iconfinder.com/data/icons/avatars-xmas-giveaway/128/afro_woman_female_person-512.png',                }}></Thumbnail><View style={styles.nameNumber}><Text style={styles.userName}>{userName}</Text></View><View style={styles.deleteButtonContainer}><Button                  rounded                  style={styles.deleteButton}                  onPress={() => onDeleteContact(item.id)}><Icon name="trash-o" size={moderateScale(20)} color="black" /></Button></View></View></TouchableOpacity>          );        },

cannot scroll down the panGestureHandler

$
0
0

I am using a react native Modal to open a PanGestureHandler that is placed inside the (UserInfoContainer) component. This is for animation. The PanGestureHandler loads but the initial height expands to almost the full page and I cannot scroll it down using the small white bar at the top.

How can I fix this? Why is the scrolling not working?

export const UserInfoContainer: React.FC<PanGestureProps> = ({ firstName, rating, numberOfFriends }) => {  const dragY = useRef(new Animated.Value(0));  const onGestureEvent = Animated.event(    [{ nativeEvent: { translationY: dragY.current } }],    {      useNativeDriver: true,    },  );  const onHandleStateChange = (event: any) => {    if (event.nativeEvent.oldState === State.ACTIVE) {      dragY.current.extractOffset();    }  };  const animateInterpolation = dragY.current.interpolate({    inputRange: [-SCREEN_HEIGHT + SCREEN_HEIGHT / 4 + SCREEN_HEIGHT / 10, 0],    outputRange: [-SCREEN_HEIGHT + SCREEN_HEIGHT / 4 + SCREEN_HEIGHT / 10, 0],    extrapolate: 'clamp',  });  const animatedStyles = {    transform: [      {        translateY: animateInterpolation,      },    ],  };  const whitelistBarMarginInterpolation = dragY.current.interpolate({    inputRange: [-SCREEN_HEIGHT + SCREEN_HEIGHT / 3, 0],    outputRange: [0, moderateScale(150)],    extrapolate: 'clamp',  });  const whitelistBarStyles = {    transform: [      {        translateY: whitelistBarMarginInterpolation,      },    ],  };  return (<PanGestureHandler      onGestureEvent={onGestureEvent}      onHandlerStateChange={onHandleStateChange}><Animated.View        style={[          styles.container,          animatedStyles,          /* { transform: [{ translateY: dragY.current }] } */        ]}><SwipeBar /><View style={styles.introContainer}><Text style={styles.name}>            {firstName}</Text><Animated.View style={[styles.whitelistBar, whitelistBarStyles]}></Animated.View></Animated.View></PanGestureHandler>  );};

enter image description here

The white background is from the modal. The greyish one is the pan gesture handler.


unable to use Font Awesome Icons in React Native

$
0
0

I am trying to use font awesome icons in my app but only some of them work while others give an error and show up as a question mark.

For example, these work:

import Icon from 'react-native-vector-icons/FontAwesome';<Icon              name="user"              style={styles.userIcon}              size={moderateScale(20)}            /><Icon name="star" size={moderateScale(13)} />

But this does not:

<View><Icon name="smoking" color="green"></Icon></View>

Even though all of these icons are present here in this directory:

https://fontawesome.com/icons?d=gallery&q=smoking

Secondly, how can I use the light version of an icon? For example, the user icon that I am using is filled. How can I change it to the light one as shown in the directory search? Both of them have same names.

move a horizontal line to the center in StyledSheets

$
0
0

I have drawn a horizontal line like this. However, it appears towards the left side of the screen. I don't want to increase the width. How else can I move it to the center? I tried wrapping it with another view along with alignContent: 'center' etc but it didn't work for me.

<View style={styles.horizontalLine}></View>
  horizontalLine: {    marginTop: 25,    width: '80%',    height: 1,    //alignContent: 'center',    //width: 1,    backgroundColor: '#E0E0E0',  },

enter image description here

make text double bold - scaled sheets

$
0
0

Is there any way to increase the intensity of the bold-ness of apply it twice?

I am using this styling on my text:

  numbers: {    fontSize: 30,    color: '#31C283',    fontWeight: 'bold',  },

Is it possible to make it double/more bold without increasing the font size?

How to do a counter that not count when I drag element to empty place on the same grid (side)

$
0
0

I have a problemI split the screen into two partsOne half have images by grid and the other half is emptyI do dragging from one another

What conditions should I place to make sure that no part of my grid is empty?

 drop(ev, index) {    ev.preventDefault();    const data = ev.dataTransfer.getData('text');    ev.dataTransfer.setData('text', ev.target.id);    if ( ev.target.id === 'emptySide1') {      ev.target.appendChild(document.getElementById(data));      this.cnt--;    } else if ( ev.target.id === 'emptySide2') {      ev.target.appendChild(document.getElementById(data));      this.item[index] = this.img[this.index];      this.cnt++;    }       this.btnContent = (this.cnt === this.img.length) ? 'continue : fill the empty place';  }
<div class="wrapper"><div class="wrapper2"><div class="box" id="emptySide1" *ngFor="let image of img let i = index" (drop)="drop($event,i)"    (dragover)="allowDrop($event)"><img  [src]="image.name" width="100%" height="150" draggable="true" (dragstart)="drag($event, i)" [id]="image.id"></div></div><div class="border-left"></div><div id="mycanvas" class="wrapper3"><div class="box2" id="emptySide2" *ngFor="let image of img let i = index" (drop)="drop($event,i)"    (dragover)="allowDrop($event)"></div></div></div><button class="btn" (click)="loopitem()" [disabled]="cnt !== img.length">{{this.btnContent}}</button>

Change RN code from function component Typescript to normal react native component

$
0
0

I'm creating a video player and I have to set controls. I found this tutorial https://medium.com/prototyped/react-native-video-handling-fullscreen-and-controls-on-android-dbb45a2e52ea][1]

but in this tutorial, all code is in typescript and he use a function component. how can I migrate to normal react native class system for example for this code:

import React from 'react';import Slider from '@react-native-community/slider';import {View, Text, StyleSheet} from 'react-native';interface Props {  currentTime: number;  duration: number;  onSlideCapture: (data: {seekTime: number}) => void;  onSlideStart: () => void;  onSlideComplete: () => void;}export const ProgressBar: React.FC<Props> = ({  currentTime,  duration,  onSlideCapture,  onSlideStart,  onSlideComplete,}) => {  const position = getMinutesFromSeconds(currentTime);  const fullDuration = getMinutesFromSeconds(duration);  return (<View style={styles.wrapper}><Slider        value={currentTime}        minimumValue={0}        maximumValue={duration}        step={1}        onValueChange={handleOnSlide}        onSlidingStart={onSlideStart}        onSlidingComplete={onSlideComplete}        minimumTrackTintColor={'#F44336'}        maximumTrackTintColor={'#FFFFFF'}        thumbTintColor={'#F44336'}      /><View style={styles.timeWrapper}><Text style={styles.timeLeft}>{position}</Text><Text style={styles.timeRight}>{fullDuration}</Text></View></View>  );  function getMinutesFromSeconds(time: number) {    const minutes = time >= 60 ? Math.floor(time / 60) : 0;    const seconds = Math.floor(time - minutes * 60);    return `${minutes >= 10 ? minutes : '0'+ minutes}:${      seconds >= 10 ? seconds : '0'+ seconds    }`;  }  function handleOnSlide(time: number) {    onSlideCapture({seekTime: time});  }};

specially interface prop...

Viewing all 6218 articles
Browse latest View live


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