react-native#Text TypeScript Examples

The following examples show how to use react-native#Text. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DropList.tsx    From frontatish with MIT License 7 votes vote down vote up
DropList = (props: DropListProps) => {
  const { items, active, onChange, itemStyle } = props;
  const Colors = useColors();
  const styles = getStyles(Colors);
  const renderItem = ({ item, index }: { item: DropItem; index: number }) => {
    return (
      <TouchableOpacity onPress={() => onChange(index)}>
        <View
          style={{
            backgroundColor: active === index ? Colors.font_6 : Colors.white,
            padding: 16,
          }}
        >
          <Text style={{ color: Colors.font_2, ...itemStyle }}>
            {item?.label ?? item}
          </Text>
        </View>
        {index < items.length - 1 && <Line />}
      </TouchableOpacity>
    );
  };

  return (
    <View style={styles.listContainer}>
      <FlatList
        data={items}
        // contentContainerStyle={styles.listContainer}
        renderItem={renderItem}
        keyExtractor={(item) => item?.label ?? item}
        persistentScrollbar
      />
    </View>
  );
}
Example #2
Source File: index.tsx    From SpotifyClone with MIT License 7 votes vote down vote up
AlbumCategory = (props: AlbumCategoryProps) => (
  <View style={styles.container}>
    <Text style={styles.title}>{props.title}</Text>
    <FlatList
      data={props.albums}
      renderItem={({ item }) => <AlbumComponent album={item} />}
      keyExtractor={( item ) => item.id}
      showsHorizontalScrollIndicator={false}
      horizontal
    />
  </View>
)
Example #3
Source File: Usernames.tsx    From ReactNative-UIKit with MIT License 6 votes vote down vote up
Username = (props: {user: UidInterface; style?: React.CSSProperties}) => {
  const {usernames} = useContext(RtmContext);
  const {rtmProps, styleProps} = useContext(PropsContext);
  const {user} = props;

  return rtmProps?.displayUsername ? (
    <Text style={[styles.username, styleProps?.usernameText]}>
      {usernames[user.uid]}
    </Text>
  ) : (
    <React.Fragment />
  );
}
Example #4
Source File: index.snapshot.test.tsx    From react-native-masonry-scrollview with MIT License 6 votes vote down vote up
VMasonryComponentThreeColumns = () => {
  return (
    <RNMasonryScrollView>
      {[
        <Text key={1}>{column1Text}</Text>,
        <Text key={2}>{column2Text}</Text>,
        <Text key={3}>{column3Text}</Text>
      ]}
    </RNMasonryScrollView>
  );
}
Example #5
Source File: Header.tsx    From happy with MIT License 6 votes vote down vote up
export default function Header({ title, showCancel = true }: HeaderProps) {
  const navigation = useNavigation();

  function handleGoBackToAppHomePage() {
    navigation.navigate('OrphanagesMap');
  }

  return (
    <View style={styles.container}>
      <BorderlessButton onPress={navigation.goBack}>
        <Feather name="arrow-left" size={24} color="#15b6d6" />
      </BorderlessButton>

      <Text style={styles.title}>{title}</Text>

      {showCancel ? (
        <BorderlessButton onPress={handleGoBackToAppHomePage}>
          <Feather name="x" size={24} color="#ff669d" />
        </BorderlessButton>
      ) : (
        <View />
      )}
    </View>
  );
}
Example #6
Source File: FlutterwaveCheckout.tsx    From flutterwave-react-native with MIT License 6 votes vote down vote up
FlutterwaveCheckoutError: React.FC<FlutterwaveCheckoutErrorProps> = ({
  hasLink,
  onTryAgain
}): React.ReactElement => {
  return (
    <View style={styles.error} testID="flw-checkout-error">
      {hasLink ? (
        <>
          <Text style={styles.errorText}>
            An error occurred, please tab below to try again.
          </Text>
          <TouchableOpacity style={styles.errorActionButton} onPress={onTryAgain}>
            <Text style={styles.errorActionButtonText}>Try Again</Text>
          </TouchableOpacity>
        </>
      ) : (
        <Text style={styles.errorText}>
          An error occurred, please close the checkout dialog and try again.
        </Text>
      )}
    </View>
  );
}
Example #7
Source File: EmptyStatesExample.tsx    From frontatish with MIT License 6 votes vote down vote up
EmptyStates = ({ navigation }: any) => {
  const emptyScreenComponentScreens = [
    'EmptyStateGeneric',
    'EmptyStateMFWatchlist',
    'EmptyStateStocksWatchlist',
    'EmptyStateOrders',
    'EmptyStateMFDashboard',
    'EmptyStateStocksDashboard',
    'EmptyStateCart',
  ];
  const Colors = useColors();
  return (
    <SafeAreaView style={{ flex: 1, backgroundColor: Colors.white }}>
      <ScrollView
        showsVerticalScrollIndicator={false}
        contentContainerStyle={{ flexGrow: 1 }}
      >
        {emptyScreenComponentScreens.map((item) => (
          <TouchableOpacity
            onPress={() => navigation.navigate(item)}
            style={[
              styles.navButtonContainer,
              { borderBottomColor: Colors.font_3 },
            ]}
            key={item}
          >
            <Text style={{ color: Colors.font_1 }}>{item}</Text>
          </TouchableOpacity>
        ))}
      </ScrollView>
    </SafeAreaView>
  );
}
Example #8
Source File: PrimaryButton.tsx    From jmix-frontend with Apache License 2.0 6 votes vote down vote up
PrimaryButton: FunctionComponent<PrimaryButtonProps> = ({ onPress, loading, style, disabled, children }) => {
  return (
    <View style={style}>
      <TouchableOpacity style={[
                          styles.button,
                          disabled && {opacity: 0.5}
                        ]}
                        onPress={onPress}
                        disabled={disabled}
      >
        {loading ? (
          <ActivityIndicator color={colors.textInverted}/>
        ) : (
          <Text style={styles.text}>{children}</Text>
        )}
      </TouchableOpacity>
    </View>
  );
}
Example #9
Source File: Button.tsx    From companion-kit with MIT License 6 votes vote down vote up
render() {
        const { disabled, title, style, titleStyles, withBorder, underlayColor, isTransparent, buttonForm } = this.props;
        const btnUnderlayColor = () => {
            if (isTransparent) {
                return Colors.borderColor;
            }
            if (buttonForm) {
                return Colors.button.buttonForm.underlay;
            }
            return Colors.button.defaultUnderlayColor;
        };

        return (
            <TouchableHighlight
                style={[ styles.button, disabled && styles.disabledButton, withBorder && styles.withBorder, isTransparent && styles.buttonTransparent, buttonForm && styles.buttonForm, style ]}
                onPress={this._onPressHandler}
                underlayColor={underlayColor ? underlayColor : btnUnderlayColor()}
                activeOpacity={1}
                disabled={disabled}
            >
                { title
                    ? <Text style={[TextStyles.btnTitle, disabled && styles.disabledText, isTransparent ? { color: Colors.button.transparentText } : {}, buttonForm && styles.buttonFormText, titleStyles]}>
                        {title}
                    </Text>
                    : <>{this.props.children}</>
                }
            </TouchableHighlight>
        );
    }
Example #10
Source File: DetailScreen.tsx    From react-native-sdk with MIT License 6 votes vote down vote up
render() {
    const coffee = this.props.route.params.coffee
    return (
      <View style={styles.container}>
        <Image resizeMode="contain" style={styles.image} source={coffee.icon} />
        <Text style={styles.text}>{coffee.name}. {coffee.subtitle}</Text>
        <Button buttonStyle={styles.button} titleStyle={styles.buttonText} title="Buy Now" onPress={this.buyTapped} />
      </View>
    )
  }
Example #11
Source File: note-link.tsx    From protect-scotland with Apache License 2.0 6 votes vote down vote up
NoteLink: FC<NoteLink> = ({
  background = colors.darkGrey,
  link,
  text
}) => {
  const {t} = useTranslation();
  const handle = () => {
    WebBrowser.openBrowserAsync(t(link), {
      enableBarCollapsing: true,
      showInRecents: true
    });
  };

  return (
    <TouchableWithoutFeedback onPress={handle}>
      <View style={[styles.container, {borderColor: background}]}>
        <View style={[styles.icon, {backgroundColor: background}]}>
          <Image
            source={IconNote}
            width={36}
            height={36}
            resizeMethod="resize"
            resizeMode="contain"
            accessibilityIgnoresInvertColors={false}
          />
        </View>
        <View style={styles.textContainer}>
          <Text style={[styles.text, styles.heading, {color: background}]}>
            {t(text)}
          </Text>
        </View>
      </View>
    </TouchableWithoutFeedback>
  );
}
Example #12
Source File: App.tsx    From Rapid-Application-Development-with-AWS-Amplify with MIT License 6 votes vote down vote up
App = () => {

  const [authState, setAuthState] = React.useState<any>();
  const [user, setUser] = React.useState<any | undefined>();

  const setCurrentUser = () => {
    Auth.currentAuthenticatedUser()
      .then((user: any) => {
        setUser(user);
      })
      .catch((info: any) => {
        console.log("Info: ", info);
      });
  };

  return (authState && user) ? (
    <View style={styles.container}>
      <Text>Good day, {(authState && user) ? user.username : 'mate'}</Text>
      <Button title="Sign out" onPress={() => {
        Auth.signOut().then(
          () => {
            setAuthState(null);
            setUser(null);
          }
        ).catch((info: any) => console.log("Info: ", info));
      }} />
    </View>
  ) : (
      <Authenticator
        signUpConfig={signUpConfig}
        onStateChange={(authState: any) => {
          setAuthState(authState);
          setCurrentUser();
        }}
        theme={GreatTheme}
      />

    );
}
Example #13
Source File: Badge.tsx    From react-native-design-kit with MIT License 6 votes vote down vote up
export default function Badge({
  containerStyle,
  style,
  value,
  size = 18,
  color = 'red',
  children,
}: BadgeProps) {
  const handleRenderContent = useMemo(() => {
    const content = value !== undefined ? value : children;

    return typeof content === 'string' || typeof content === 'number' ? (
      <Text style={StyleSheet.flatten([styles.text, style])}>{content}</Text>
    ) : (
      content
    );
  }, [value, children, style]);

  return (
    <View
      style={StyleSheet.flatten([
        styles.container,
        containerStyle,
        {height: size, minWidth: size, borderRadius: size / 2},
        color !== undefined && {backgroundColor: 'red'},
      ])}>
      {handleRenderContent}
    </View>
  );
}
Example #14
Source File: index.tsx    From SpotifyClone with MIT License 6 votes vote down vote up
AlbumComponent = (props: AlbumProps) => {

  const navigation = useNavigation();

  const onPress = () => {
    navigation.navigate('AlbumScreen', { id: props.album.id })
  }

  return (
    <TouchableWithoutFeedback onPress={onPress}>
      <View style={styles.container}>
          <Image source={{uri: props.album.imageUri}} style={styles.image}/>
          <Text style={styles.text}>{props.album.artistsHeadline}</Text>
      </View>
    </TouchableWithoutFeedback>

  )
}
Example #15
Source File: index.tsx    From TwitterClone with MIT License 6 votes vote down vote up
FleetView = (props: FleetViewProps) => {
  const { user, fleet, goToNextFleet, goToPrevFleet } = props;
  return (
    <View style={styles.container}>

      {fleet.image && <Image source={{ uri: fleet.image}} style={styles.image}/>}
      <Text style={styles.text}>{fleet.text}</Text>

      <View style={styles.userHeaderContainer}>
        <ProfilePicture image={user.image} size={70} />
        <View style={styles.userNames}>
          <Text style={styles.name}>{user.name}</Text>
          <View style={{flexDirection: 'row'}}>
            <Text style={styles.username}>
              @{user.username}
            </Text>
            <Text style={styles.time}>
              {moment(fleet.createdAt).fromNow()}
            </Text>
          </View>
        </View>
      </View>

      <View style={styles.buttonContainer}>
        <TouchableOpacity style={{flex: 1}} onPress={() => goToPrevFleet()} />
        <TouchableOpacity style={{flex: 1}} onPress={() => goToNextFleet()} />
      </View>

    </View>
  )
}
Example #16
Source File: AppBar.tsx    From SQL-Play with GNU Affero General Public License v3.0 6 votes vote down vote up
AppBar: React.FC<Props> = ({
  setInputValue,
  isPremium,
  setIsPremium,
  setPremiumModalOpen,
  premiumModalOpen,
}) => {
  // console.log(premiumModalOpen);
  return (
    <View style={styles.appBar} accessibilityLabel="app bar">
      <Text style={styles.appBarTxt} accessibilityLabel="SQL Play">
        SQL Play
      </Text>
      <View style={styles.optionContainer}>
        <SearchBox setInputValue={setInputValue} />
        <MenuOptions
          isPremium={isPremium}
          setInputValue={setInputValue}
          setIsPremium={setIsPremium}
          setPremiumModalOpen={setPremiumModalOpen}
          premiumModalOpen={premiumModalOpen}
        />
      </View>
    </View>
  );
}
Example #17
Source File: gitlab.tsx    From THUInfo with MIT License 6 votes vote down vote up
BranchItem = ({
	name,
	onPress,
}: {
	name: string;
	onPress: (event: GestureResponderEvent) => void;
}) => {
	const themeName = useColorScheme();
	const {colors} = themes(themeName);
	const content = (
		<View
			style={{
				padding: 8,
				paddingRight: 16,
				flexDirection: "row",
				justifyContent: "space-between",
			}}>
			<Text style={{fontSize: 17, marginHorizontal: 10, color: colors.text}}>
				{name}
			</Text>
		</View>
	);
	return Platform.OS === "ios" ? (
		<TouchableHighlight underlayColor="#0002" onPress={onPress}>
			{content}
		</TouchableHighlight>
	) : (
		<TouchableNativeFeedback
			background={TouchableNativeFeedback.Ripple("#0002", false)}
			onPress={onPress}>
			{content}
		</TouchableNativeFeedback>
	);
}
Example #18
Source File: BtnTemplate.tsx    From ReactNative-UIKit with MIT License 5 votes vote down vote up
BtnTemplate: React.FC<BtnTemplateInterface> = (props) => {
  const {disabled = false} = props;
  const {styleProps} = useContext(PropsContext);
  const {BtnTemplateStyles, theme, iconSize, customIcon} = styleProps || {};

  const imageRef = React.useRef(null);

  // This fixes the tint issue in safari browser
  useImageDelay(imageRef, 10, '', props?.color || '');

  return (
    <TouchableOpacity
      style={styleProps?.BtnTemplateContainer}
      disabled={disabled}
      onPress={props.onPress}>
      <View
        style={[
          {...styles.controlBtn, ...(BtnTemplateStyles as object)},
          props.style as object,
        ]}>
        <Image
          ref={Platform.OS === 'web' ? imageRef : undefined}
          style={{
            width: iconSize || 25,
            height: iconSize || 25,
            opacity: disabled ? 0.4 : 1,
            tintColor: disabled ? 'grey' : props.color || theme || '#fff',
          }}
          resizeMode={'contain'}
          source={{
            uri: props.name
              ? customIcon?.[props.name]
                ? customIcon[props.name]
                : icons[props.name]
              : props.icon,
          }}
        />
      </View>
      <Text
        style={{
          textAlign: 'center',
          marginTop: 5,
          color: disabled ? 'grey' : props.color || theme || '#fff',
          opacity: disabled ? 0.4 : 1,
        }}>
        {props.btnText}
      </Text>
    </TouchableOpacity>
  );
}
Example #19
Source File: App.tsx    From react-native-detector with MIT License 5 votes vote down vote up
export default function App() {
  const [screenshotCounter, setScreenshotCounter] = React.useState<number>(0);

  React.useEffect(() => {
    const requestPermission = async () => {
      try {
        const granted = await PermissionsAndroid.request(
          PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,
          {
            title: 'Get Read External Storage Access',
            message:
              'get read external storage access for detecting screenshots',
            buttonNeutral: 'Ask Me Later',
            buttonNegative: 'Cancel',
            buttonPositive: 'OK',
          }
        );
        if (granted === PermissionsAndroid.RESULTS.GRANTED) {
          console.log('You can use the READ_EXTERNAL_STORAGE');
        } else {
          console.log('READ_EXTERNAL_STORAGE permission denied');
        }
      } catch (err) {
        console.warn(err);
      }
    };
    if (Platform.OS === 'android') {
      requestPermission();
    }
    const userDidScreenshot = () => {
      setScreenshotCounter((screenshotCounter) => screenshotCounter + 1);
    };
    const unsubscribe = addScreenshotListener(userDidScreenshot);
    return () => {
      unsubscribe();
    };
  }, []);

  return (
    <View style={styles.container}>
      <Text>User took {screenshotCounter} screenshot</Text>
    </View>
  );
}
Example #20
Source File: TextWithCursor.tsx    From react-native-currency-input with MIT License 5 votes vote down vote up
TextWithCursor = (textWithCursorProps: TextWithCursorProps) => {
  const { children, cursorVisible, style, cursorProps, ...rest } = textWithCursorProps;

  const blinkVisible = useBlink();

  const [isTyping, setIsTyping] = React.useState(false);

  const timeout = React.useRef<NodeJS.Timeout>();

  const cursorVisibility = React.useMemo(() => {
    return cursorVisible && (blinkVisible || isTyping);
  }, [blinkVisible, cursorVisible, isTyping]);

  const cursorFontSize = React.useMemo(() => {
    return StyleSheet.flatten([styles.text, style]).fontSize || 18;
  }, [style]);

  React.useEffect(() => {
    setIsTyping(true);
    timeout.current = setTimeout(() => {
      setIsTyping(false);
    }, 500);

    return () => {
      timeout.current && clearTimeout(timeout.current);
    };
  }, [children]);

  return (
    <Text style={[styles.text, style]} {...rest}>
      {children}
      <Text
        {...cursorProps}
        style={[
          {
            fontSize: cursorFontSize * (cursorFontSize < 26 ? 1.42 : 1.25),
          },
          styles.cursor,
          cursorProps?.style,
          !cursorVisibility ? styles.cursorHidden : undefined,
        ]}
      >
        |
      </Text>
    </Text>
  );
}
Example #21
Source File: index.tsx    From react-native-floating-label-input with MIT License 5 votes vote down vote up
AnimatedText = Animated.createAnimatedComponent(Text)
Example #22
Source File: Button.tsx    From mobile with Apache License 2.0 5 votes vote down vote up
Button = ({
  text,
  onPress,
  variant,
  color: buttonColorName,
  disabled,
  loading,
  externalLink,
}: ButtonProps) => {
  const [i18n] = useI18n();
  const theme = useTheme<Theme>();
  const variantProps = theme.buttonVariants[variant];
  const disabledProps = disabled ? variantProps.disabled || {} : {};
  const themedStyles = {...variantProps, ...disabledProps};
  const {fontSize, fontWeight, fontFamily, color, borderWidth, height} = (themedStyles as unknown) as TextStyle &
    ViewStyle;
  const textColor = themedStyles.textColor;
  const buttonColor = buttonColorName && theme.colors[buttonColorName];

  const onPressHandler = loading ? () => {} : onPress;
  const externalLinkProps = externalLink
    ? {
        accessibilityLabel: text,
        accessibilityHint: i18n.translate('Home.ExternalLinkHint'),
        accessibilityRole: 'link' as AccessibilityRole,
      }
    : {};
  const externalArrowIcon = textColor === palette.white ? 'icon-external-arrow-light' : 'icon-external-arrow';

  const content = (
    <Box
      borderRadius={4}
      alignItems="center"
      justifyContent="center"
      style={{backgroundColor: color, minHeight: height, borderWidth, borderColor: buttonColor}}
      paddingHorizontal="m"
      flexDirection="row"
    >
      {loading ? (
        <ActivityIndicator color={textColor} size="large" />
      ) : (
        <>
          <Text style={{...styles.content, color: textColor || buttonColor, fontWeight, fontFamily, fontSize}}>
            {text}
          </Text>
          {externalLink && <Icon name={externalArrowIcon} />}
        </>
      )}
    </Box>
  );

  const accessibilityProps = {
    accessibilityRole: 'button' as 'button',
    accessibilityState: {disabled},
    ...externalLinkProps,
  };

  if (Platform.OS === 'android') {
    return (
      <Ripple rippleContainerBorderRadius={4} onPress={onPressHandler} {...accessibilityProps}>
        {content}
      </Ripple>
    );
  }
  return (
    <TouchableOpacity onPress={onPressHandler} style={styles.stretch} disabled={disabled} {...accessibilityProps}>
      {content}
    </TouchableOpacity>
  );
}
Example #23
Source File: App.tsx    From react-native-masonry-scrollview with MIT License 5 votes vote down vote up
App = () => {
  const imageWidth: number = useResponsiveWidth(50) - 20;
  const [isHorizontal, setIsHorizontal] = useState<boolean>(false);

  const toggleHorizontal = () => setIsHorizontal(!isHorizontal);

  const imageProp = isHorizontal
    ? { height: imageWidth }
    : { width: imageWidth };

  return (
    <SafeAreaView>
      <View style={styles.header}>
        <Switch onValueChange={toggleHorizontal} value={isHorizontal} />
        <Text style={styles.headerText}>Horizontal</Text>
      </View>
      <RNMasonryScroll
        removeClippedSubviews={true}
        columns={isHorizontal ? 3 : 2}
        evenColumnStyle={styles.evenColumnStyle}
        oddColumnStyle={
          isHorizontal
            ? styles.oddColumnStyleHorizontal
            : styles.oddColumnStyleVertical
        }
        horizontal={isHorizontal}
      >
        {images.map((image, imageIndex) => {
          return (
            <AnimatableView
              animation={isHorizontal ? "fadeInRight" : "fadeInUp"}
              delay={100 * imageIndex}
              style={styles.imageContainer}
            >
              <Image source={{ uri: image }} {...imageProp} key={imageIndex} />
            </AnimatableView>
          );
        })}
      </RNMasonryScroll>
    </SafeAreaView>
  );
}
Example #24
Source File: index.tsx    From NLW-1.0 with MIT License 5 votes vote down vote up
Detail: React.FC = () => {
  const [data, setData] = useState<Data>({} as Data);
  const navigation = useNavigation();
  const route = useRoute();

  const routeParams = route.params as Params;

  useEffect(() => {
    async function loadPoint() {
      const response = await api.get(`/points/${routeParams.point_id}`);

      setData(response.data);
    }

    loadPoint();
  }, []);

  function handleNavigateBack() {
    navigation.goBack();
  }

  function handleComposeMail() {
    MailComposer.composeAsync({
      subject: "Interesse na coleta de resíduos",
      recipients: [data.point.email],
    });
  }

  function handleWhatsApp() {
    Linking.openURL(
      `whatsapp://send?phone=${data.point.whatsapp}&text=Tenho interesse na coleta de resíduos`
    );
  }
  if (!data.point) {
    return null;
  }

  return (
    <SafeAreaView style={{ flex: 1 }}>
      <View style={styles.container}>
        <TouchableOpacity onPress={handleNavigateBack}>
          <Icon name="arrow-left" size={20} color="#34cb79" />
        </TouchableOpacity>

        <Image
          style={styles.pointImage}
          source={{
            uri: data.point.image_url,
          }}
        />

        <Text style={styles.pointName}>{data.point.name}</Text>
        <Text style={styles.pointItems}>
          {data.items.map((item) => item.title).join(",")}
        </Text>

        <View style={styles.address}>
          <Text style={styles.addressTitle}>Endereço</Text>
          <Text style={styles.addressContent}>
            {data.point.city}, {data.point.uf}
          </Text>
        </View>
      </View>
      <View style={styles.footer}>
        <RectButton style={styles.button} onPress={() => handleWhatsApp()}>
          <FontAwesome name="whatsapp" size={20} color="#fff" />
          <Text style={styles.buttonText}>Whatsapp</Text>
        </RectButton>
        <RectButton style={styles.button} onPress={() => handleComposeMail()}>
          <Icon name="mail" size={20} color="#fff" />
          <Text style={styles.buttonText}>E-mail</Text>
        </RectButton>
      </View>
    </SafeAreaView>
  );
}
Example #25
Source File: SelectMapPosition.tsx    From happy with MIT License 5 votes vote down vote up
export default function SelectMapPosition() {
  const navigation = useNavigation();
  const [position, setPosition] = useState({ latitude: 0, longitude: 0});

  function handleNextStep() {
    navigation.navigate('OrphanageData', { position });
  }

  function handleSelectMapPosition(event: MapEvent) {
    setPosition(event.nativeEvent.coordinate);
  }

  return (
    <View style={styles.container}>
      <MapView
        initialRegion={{
          latitude: -27.2092052,
          longitude: -49.6401092,
          latitudeDelta: 0.008,
          longitudeDelta: 0.008,
        }}
        style={styles.mapStyle}
        onPress={handleSelectMapPosition}
      >
        {position.latitude !== 0 && (
          <Marker
            icon={mapMarkerImg}
            coordinate={{ latitude: position.latitude, longitude: position.longitude }}
          />
        )}
      </MapView>

      {position.latitude !== 0 && (
        <RectButton style={styles.nextButton} onPress={handleNextStep}>
          <Text style={styles.nextButtonText}>Próximo</Text>
        </RectButton>
      )}
    </View>
  )
}
Example #26
Source File: cart.spec.tsx    From rocketseat-gostack-11-desafios with MIT License 5 votes vote down vote up
TestComponent: React.FC = () => {
  const { products, addToCart, increment, decrement } = useCart();

  function handleAddToCart(): void {
    addToCart({
      id: '1234',
      title: 'Test product',
      image_url: 'test',
      price: 1000,
      quantity: 0,
    });
  }

  function handleIncrement(): void {
    increment('1234');
  }

  function handleDecrement(): void {
    decrement('1234');
  }

  return (
    <>
      <TouchableOpacity testID="add-to-cart" onPress={handleAddToCart}>
        Add to cart
      </TouchableOpacity>

      <TouchableOpacity testID="increment" onPress={handleIncrement}>
        Increment
      </TouchableOpacity>

      <TouchableOpacity testID="decrement" onPress={handleDecrement}>
        Decrement
      </TouchableOpacity>

      {products.map(product => (
        <View key={product.id}>
          <Text>{product.title}</Text>
          <Text>{product.quantity}</Text>
        </View>
      ))}
    </>
  );
}
Example #27
Source File: FlutterwaveButton.spec.tsx    From flutterwave-react-native with MIT License 5 votes vote down vote up
describe('<FlutterwaveButton/>', () => {
  it('renders pay with flutterwave by default', () => {
    // create test renderer
    const TestRenderer = renderer.create(<FlutterwaveButton />);
    // run assertions
    expect(TestRenderer.toJSON()).toMatchSnapshot();
  });

  it('renders with overlay and inactive style of button is disabled', () => {
    // create test renderer
    const TestRenderer = renderer.create(<FlutterwaveButton disabled />);
    // run assertions
    expect(TestRenderer.toJSON()).toMatchSnapshot();
  });

  it('applies left aligned style if alignLeft prop is present', () => {
    // create test renderer
    const TestRenderer = renderer.create(<FlutterwaveButton alignLeft />);
    // run assertions
    expect(TestRenderer.toJSON()).toMatchSnapshot();
  });

  it('replaces pay with flutterwave image with children', () => {
    // create test renderer
    const TestRenderer = renderer.create(
      <FlutterwaveButton>
        <Text>Hello, World!</Text>
      </FlutterwaveButton>
    );
    // run assertions
    expect(TestRenderer.toJSON()).toMatchSnapshot();
  });

  it('fires on press if set', () => {
    // create onPress function
    const onPress = jest.fn();
    // create test renderer
    const TestRenderer = renderer.create(
      <FlutterwaveButton onPress={onPress}>
        <Text>Hello, World!</Text>
      </FlutterwaveButton>
    );
    // fire onPress function
    TestRenderer.root.findByProps({testID}).props.onPress();
    // run assertions
    expect(TestRenderer.root.findByProps({testID}).props.onPress).toBeDefined();
    expect(onPress).toBeCalledTimes(1);
  });
});
Example #28
Source File: ButtonExample.tsx    From frontatish with MIT License 5 votes vote down vote up
ButtonExample = () => {
  const Colors = useColors();
  const [loading, setLoading] = useState(false);
  const handlePress = () => {
    // do some action
    setLoading(!loading);
  };
  return (
    <SafeAreaView style={{ flex: 1, backgroundColor: Colors.white }}>
      <View style={styles.exampleBtnContainer}>
        <Text style={{ color: Colors.font_1, fontSize: Fonts.size.h3 }}>
          Button Examples
        </Text>
        <View style={{ flexDirection: 'row', marginVertical: 20 }}>
          <Button
            type="primary"
            onPress={handlePress}
            label="Primary Button"
            customStyles={{ flex: 1, marginRight: 20 }}
          />
          <Button
            type="secondary"
            onPress={handlePress}
            label="Secondary Button"
            customStyles={{ flex: 1 }}
          />
        </View>
        <View style={{ flexDirection: 'row', marginVertical: 20 }}>
          <Button
            type="primary"
            onPress={handlePress}
            label="Primary Disabled"
            customStyles={{ flex: 1, marginRight: 20 }}
            disabled
          />
          <Button
            type="secondary"
            onPress={handlePress}
            label="Secondary Disabled"
            disabled
            customStyles={{ flex: 1 }}
          />
        </View>
        <View style={{ marginVertical: 20 }}>
          <Button
            type="primary"
            onPress={handlePress}
            label="Loading Button"
            loading={loading}
          />
        </View>
      </View>
    </SafeAreaView>
  );
}