react-native#Linking TypeScript Examples

The following examples show how to use react-native#Linking. 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: UnknownProblemView.tsx    From mobile with Apache License 2.0 6 votes vote down vote up
UnknownProblemView = ({isBottomSheetExpanded}: {isBottomSheetExpanded: boolean}) => {
  const i18n = useI18n();

  const onHelp = useCallback(() => {
    Linking.openURL(i18n.translate('Info.HelpUrl')).catch(error => captureException('An error occurred', error));
  }, [i18n]);

  const autoFocusRef = useAccessibilityAutoFocus(!isBottomSheetExpanded);
  return (
    <BaseHomeView iconName="error-icon" testID="unknownProblem">
      <Text focusRef={autoFocusRef} variant="bodyTitle" color="darkText" marginBottom="m" accessibilityRole="header">
        {i18n.translate('Home.UnknownProblem.Title')}
      </Text>
      <Text marginBottom="m" variant="bodyDescription" color="lightText">
        {i18n.translate('Home.UnknownProblem.Body')}
      </Text>
      <Box alignSelf="stretch" marginBottom="m" marginTop="l">
        <ButtonSingleLine
          text={i18n.translate('Home.UnknownProblem.CTA')}
          variant="danger50Flat"
          externalLink
          onPress={onHelp}
        />
      </Box>
    </BaseHomeView>
  );
}
Example #2
Source File: push-notifications.tsx    From protect-scotland with Apache License 2.0 6 votes vote down vote up
PushNotificationsModal: FC<ModalProps> = (props) => {
  const {t} = useTranslation();
  return (
    <Modal
      {...props}
      title={t('modals:sendNotifications:title')}
      type="dark"
      buttons={[
        {
          variant: 'inverted',
          action: Linking.openSettings,
          hint: t('modals:sendNotifications:btnLabel'),
          label: t('modals:sendNotifications:btnLabel')
        }
      ]}>
      <Markdown markdownStyles={modalMarkdownStyles}>
        {t('modals:sendNotifications:instructions', {name: t('common:name')})}
      </Markdown>
    </Modal>
  );
}
Example #3
Source File: ReceiveSharingIntent.ts    From react-native-receive-sharing-intent with MIT License 6 votes vote down vote up
getReceivedFiles(handler: Function, errorHandler: Function, protocol: string = "ShareMedia"){
        if(this.isIos){
            Linking.getInitialURL().then((res:any) => {
                if (res && res.startsWith(`${protocol}://dataUrl`) && !this.isClear) {
                    this.getFileNames(handler, errorHandler, res);
                }
            }).catch(() => { });
            Linking.addEventListener("url", (res:any) => {
                const url = res ? res.url : "";
                if (url.startsWith(`${protocol}://dataUrl`) && !this.isClear) {
                    this.getFileNames(handler,errorHandler, res.url);
                }
            });
        }else{
            AppState.addEventListener('change', (status: string) => {
                if (status === 'active' && !this.isClear) {
                    this.getFileNames(handler,errorHandler, "");
                }
              });
           if(!this.isClear) this.getFileNames(handler,errorHandler, "");
        }
    }
Example #4
Source File: openLink.ts    From tic-tac-toe-app with MIT License 6 votes vote down vote up
openLink = async (link: string) => {
    try {
        if (Platform.OS === 'web') {
            Linking.openURL(link);
        } else {
            await WebBrowser.openBrowserAsync(link);
        }
    } catch (err) {
        handleError(err);
    }
}
Example #5
Source File: ExposedHelpButton.tsx    From mobile with Apache License 2.0 6 votes vote down vote up
ExposedHelpButton = () => {
  const onPress = useCallback(() => {
    Linking.openURL(`https://nema.gov.mn`).catch(error => captureException('An error occurred', error));
  }, []);

  // if (cta === '') {
  //   return <ErrorBox marginTop="m" />;
  // }

  return (
    <Box alignSelf="stretch" marginTop="s" marginBottom="m">
      <ButtonSingleLine text="Тусламж авах" variant="thinFlatBlue" externalLink onPress={onPress} />
    </Box>
  );
}
Example #6
Source File: Disclaimer.tsx    From nyxo-app with GNU General Public License v3.0 6 votes vote down vote up
Disclaimer = () => {
  const openTerms = () => {
    Linking.openURL(CONFIG.TERMS_LINK)
  }

  const openPrivacyPolicy = () => {
    Linking.openURL(CONFIG.PRIVACY_LINK)
  }

  return (
    <DisclaimerContainer>
      <DisclaimerText>
        By creating a Nyxo Cloud Account, I agree to Nyxo&apos;s
        <UnderLine onPress={openTerms}> Terms of Service</UnderLine> and{' '}
        <UnderLine onPress={openPrivacyPolicy}>Privacy Policy</UnderLine>
      </DisclaimerText>
    </DisclaimerContainer>
  )
}
Example #7
Source File: Introduction.tsx    From hive-keychain-mobile with MIT License 6 votes vote down vote up
Introduction = ({navigation}: IntroductionNavProp) => {
  const {height, width} = useWindowDimensions();
  const styles = getDimensionedStyles({height, width});
  return (
    <Background>
      <>
        <Separator height={height / 15} />
        <KeychainLogo {...styles.image} />
        <Separator height={height / 20} />
        <GradientEllipse style={styles.gradient} dotColor="red">
          <Text style={styles.text}>{translate('intro.text')}</Text>
        </GradientEllipse>
        <GradientEllipse style={styles.gradient} dotColor="white">
          <Text style={styles.text}>{translate('intro.manage')}</Text>
        </GradientEllipse>
        <Separator height={height / 7.5} />
        <EllipticButton
          title={translate('intro.existingAccount')}
          onPress={() => {
            navigation.navigate('SignupScreen');
          }}
        />
        <Separator height={height / 20} />
        <EllipticButton
          title={translate('intro.createAccount')}
          onPress={() => {
            Linking.canOpenURL(hiveConfig.CREATE_ACCOUNT_URL).then(
              (supported) => {
                if (supported) {
                  Linking.openURL(hiveConfig.CREATE_ACCOUNT_URL);
                }
              },
            );
          }}
        />
      </>
    </Background>
  );
}
Example #8
Source File: Checkout.container.tsx    From RNWCShop with GNU General Public License v3.0 6 votes vote down vote up
CheckoutContainer = (): JSX.Element => {
  const products = useSelector((state: CartState) => state.products || []);
  const total = useSelector((state: CartState) => state.total || 0);

  const handleCheckoutSubmit = async (userInfo: object) => {
    const order = {
      billing: userInfo,
      shipping: userInfo,
      line_items: products.map(({ id, quantity }: CartItem) => ({
        product_id: id,
        quantity
      }))
    };
    const {
      data: { id, order_key }
    } = await WooCommerce.post('/orders', order);

    const paymentUrl =
      `${config.WC_BASE_URL}/checkout/order-pay/${id}` +
      `?pay_for_order=true&key=${order_key}`;

    return Linking.openURL(paymentUrl);
  };

  return (
    <Checkout
      handleCheckoutSubmit={handleCheckoutSubmit}
      products={products}
      total={total}
    />
  );
}
Example #9
Source File: Checkout.saga.ts    From react-native-woocommerce with MIT License 6 votes vote down vote up
export function* sendOrder({ payload: order }: { payload: object }) {
  try {
    const { id, order_key } = yield call(sendOrderAPI, order);

    if (!!id && !!order_key) {
      const paymentUrl =
          `${config.WC_BASE_URL}/checkout/order-pay/${id}?pay_for_order=true&key=${order_key}`;

      yield put(actions.checkoutResponse());
      yield Linking.openURL(paymentUrl);
    }
  } catch (error) {
    yield call(handleError, error);
  } finally {
    yield put(appActions.setRenderable());
  }
}
Example #10
Source File: AlphaWarning.tsx    From ito-app with GNU General Public License v3.0 6 votes vote down vote up
AlphaWarning: React.FC<AlphaWarningProps> = ({navigation}) => {
  const {t} = useTranslation();

  return (
    <View style={styles.container}>
      <View style={styles.logoWrapper}>
        <Text style={styles.logo}>ito</Text>
        <Text style={styles.subtitle}>track infections, not people!</Text>
        <AlphaNotice
          rootStyle={styles.alphaNoticeRoot}
          textStyle={styles.alphaNoticeText}
        />
      </View>
      <View>
        <Text style={styles.generalText}>{t('alphaWarning.demoPurpose')}</Text>
        <Text style={styles.generalText}>
          {t('alphaWarning.notFullyImplemented')}
        </Text>
        <Text style={styles.generalText}>{t('alphaWarning.review')}</Text>
      </View>
      <Text
        style={[styles.generalText, styles.githubLink]}
        onPress={(): Promise<void> =>
          Linking.openURL('https://github.com/ito-org/ito-app/issues')
        }>
        https://github.com/ito-org/ito-app/issues
      </Text>
      <View style={styles.bottomButtonContainer}>
        <Button
          title={t('alphaWarning.start')}
          onPress={(): void => navigation.navigate('Onboarding')}
          titleStyle={styles.buttonHowTitle}
          buttonStyle={styles.buttonHow}
        />
      </View>
    </View>
  );
}
Example #11
Source File: auth.ts    From solid-health with MIT License 6 votes vote down vote up
export async function init() {
  Linking.addEventListener('url', handleOpenURL);

  let url = null;
  try {
    url = await Linking.getInitialURL();
  } catch (err) {
    console.warn('Could not get initial app URL: ', err);
  }

  if (url) {
    handleOpenURL({ url });
    return;
  }

  try {
    const session = await AsyncStorage.getItem(sessionStorageKey);
    if (session) {
      await auth.setSession(JSON.parse(session));
    }
  } catch (err) {
    console.warn('Could not read saved session: ', err);
  }
}
Example #12
Source File: RootErrorBoundary.tsx    From react-native-template with MIT License 6 votes vote down vote up
showError = () => {
    Alert.alert(
      this.state.error?.name || "Error",
      this.state.error?.stack || RootErrorBoundary.NO_STACK,
      [
        {
          text: "Cancel",
          onPress: () => {
            return
          },
        },
        {
          text: "Copy & Open Issue Form",
          onPress: () => {
            const stackTrace =
              this.state.error?.stack || RootErrorBoundary.NO_STACK

            Clipboard.setString(stackTrace)

            Linking.openURL(RootErrorBoundary.ISSUE_REPORTING_URL)
          },
        },
      ],
      {
        cancelable: false,
      }
    )
  }
Example #13
Source File: phone.ts    From lets-fork-native with MIT License 6 votes vote down vote up
call = (phone: string): void => {
  let phoneNumber: string
  if (Platform.OS !== 'android') {
    phoneNumber = `telprompt:${phone}`
  } else {
    phoneNumber = `tel:${phone}`
  }
  Linking.canOpenURL(phoneNumber)
    .then((supported) => {
      if (!supported) {
        Alert.alert('Phone number is not available')
      } else {
        return Linking.openURL(phoneNumber)
      }
      return null
    })
    .catch((err) => console.log(err))
}
Example #14
Source File: App.tsx    From react-native-paper-dates with MIT License 6 votes vote down vote up
function TwitterFollowButton({ userName }: { userName: string }) {
  return (
    <Button
      uppercase={false}
      mode="outlined"
      icon="twitter"
      style={styles.twitterButton}
      onPress={() => Linking.openURL(`https://twitter.com/${userName}`)}
    >
      @{userName}
    </Button>
  )
}
Example #15
Source File: go-to-settings.tsx    From protect-scotland with Apache License 2.0 6 votes vote down vote up
goToSettingsAction = async (
  bluetoothDisabled?: boolean,
  askPermissions?: () => Promise<void>
) => {
  try {
    if (Platform.OS === 'ios') {
      Linking.openSettings();
    } else {
      bluetoothDisabled
        ? await IntentLauncher.startActivityAsync(
            IntentLauncher.ACTION_SETTINGS
          )
        : await askPermissions!();
    }
  } catch (err) {
    console.log('Error handling go to settings', err);
  }
}
Example #16
Source File: BluetoothDisabledView.tsx    From mobile with Apache License 2.0 6 votes vote down vote up
BluetoothDisabledView = () => {
  const [i18n] = useI18n();
  const toSettings = useCallback(() => {
    Linking.openSettings();
  }, []);

  return (
    <BaseHomeView>
      <Box marginBottom="l">
        <Icon name="icon-bluetooth-disabled" size={44} />
      </Box>
      <Text textAlign="center" variant="bodyTitle" color="bodyText" marginBottom="l" accessibilityRole="header">
        {i18n.translate('Home.BluetoothDisabled')}
      </Text>
      <Text variant="bodyText" color="bodyText" textAlign="center">
        {i18n.translate('Home.EnableBluetoothCTA')}
      </Text>
      <LastCheckedDisplay />
      <Box alignSelf="stretch" marginTop="l">
        <Button text={i18n.translate('Home.TurnOnBluetooth')} variant="bigFlat" onPress={toSettings} />
      </Box>
    </BaseHomeView>
  );
}
Example #17
Source File: selectCheckInType.tsx    From companion-kit with MIT License 6 votes vote down vote up
private _noCameraPermission = async () => {
        const url = 'app-settings:';
        const settingsSupported = await Linking.canOpenURL(url);

        const okButton: ModalButton = {
            text: 'OK',
            action: () => {
                this.hideModal();
                this.trigger(ScenarioTriggers.Submit);
            },
        };

        this.showModal({
            title: 'Сamera access required',
            message: (
                <View style={styles.modalMessageView}>
                    <Text style={[Layout.isSmallDevice ? TextStyles.p2 : TextStyles.p1, styles.modalMessageText]}>
                        Please re-enable it anytime in Settings and try again
                    </Text>
                </View>
            ),
            primaryButton: settingsSupported ? {
                text: 'Settings',
                action: async () => {
                    this.hideModal();
                    Linking.openURL(url);
                },
            } : okButton,
            secondaryButton: settingsSupported ? okButton : null,
        });
    }
Example #18
Source File: App.tsx    From hamagen-react-native with MIT License 6 votes vote down vote up
App = () => {
  const navigationRef = useRef<any>(null);

  useEffect(() => {
    StatusBar.setBarStyle('dark-content');

    Linking.addEventListener('url', (data) => {
      navigationRef.current && onOpenedFromDeepLink(data.url, navigationRef.current);
    });
  }, []);

  return (
    <View style={styles.container}>
      <Provider store={storeFactory()}>
        <NavigationContainer ref={navigationRef}>
          <Loading navigation={navigationRef.current} />
        </NavigationContainer>
      </Provider>
    </View>
  );
}
Example #19
Source File: new-version-card.tsx    From protect-scotland with Apache License 2.0 6 votes vote down vote up
NewVersionCard = () => {
  const {t} = useTranslation();

  const onUpdate = () => {
    Linking.openURL(
      Platform.OS === 'ios'
        ? t('newVersion:appstoreUrl')
        : t('newVersion:playstoreUrl')
    );
  };

  return (
    <TouchableWithoutFeedback onPress={onUpdate}>
      <View>
        <RoundedBox style={styles.content}>
          <Text variant="h4">
            {t('newVersion:title', {
              storeName:
                Platform.OS === 'ios'
                  ? t('newVersion:appstore')
                  : t('newVersion:playstore')
            })}
          </Text>
          <Spacing s={8} />
          <Text bold color="errorRed">
            {t('newVersion:link')}
          </Text>
        </RoundedBox>
      </View>
    </TouchableWithoutFeedback>
  );
}
Example #20
Source File: SelectInstanceHelp.tsx    From orangehrm-os-mobile with GNU General Public License v3.0 5 votes vote down vote up
onPressSupportEmail = () => {
    Linking.canOpenURL(SEND_MAIL_SUPPORT_EMAIL_URL).then((supported) => {
      if (supported) {
        Linking.openURL(SEND_MAIL_SUPPORT_EMAIL_URL);
      }
    });
  };
Example #21
Source File: ActiveSubscriptions.tsx    From nyxo-app with GNU General Public License v3.0 5 votes vote down vote up
ActiveSubscriptions: FC = () => {
  const [info, setEntitlements] = useState<
    PurchasesEntitlementInfos | undefined
  >()

  useEffect(() => {
    const fetchData = async () => {
      const { entitlements } = await Purchases.getPurchaserInfo()
      setEntitlements(entitlements)
    }
    fetchData()
  }, [])

  const handleOpenManagement = () => {
    const URL =
      Platform.OS === 'ios' ? CONFIG.MANAGE_IOS : CONFIG.MANAGE_ANDROID
    Linking.openURL(URL)
  }

  const hasActiveSubscription = info?.active['Nyxo Coaching']?.isActive

  return (
    <Container>
      {!!hasActiveSubscription && (
        <>
          <H3>SUBSCRIPTION_MANAGEMENT.CURRENTLY_ACTIVE</H3>
          {!!hasActiveSubscription && (
            <SubscriptionCard subscription={info?.active['Nyxo Coaching']} />
          )}

          <ModifyContainer>
            <ModifyButton onPress={handleOpenManagement}>
              <ModifyIcon height={15} width={15} />
              <ButtonText>JUMP_MANAGE_SUBSCRIPTION</ButtonText>
            </ModifyButton>
          </ModifyContainer>
        </>
      )}
    </Container>
  )
}
Example #22
Source File: Iterable.ts    From react-native-sdk with MIT License 5 votes vote down vote up
// PRIVATE
  private static setupEventHandlers() {
     //Remove all listeners to avoid duplicate listeners
     RNEventEmitter.removeAllListeners(EventName.handleUrlCalled)
     RNEventEmitter.removeAllListeners(EventName.handleInAppCalled)
     RNEventEmitter.removeAllListeners(EventName.handleCustomActionCalled)
     RNEventEmitter.removeAllListeners(EventName.handleAuthCalled)

    if (Iterable.savedConfig.urlHandler) {
      RNEventEmitter.addListener(
        EventName.handleUrlCalled,
        (dict) => {
          const url = dict["url"]
          const context = IterableActionContext.fromDict(dict["context"])
          Iterable.wakeApp()

          if (Platform.OS === "android") {
            //Give enough time for Activity to wake up.
            setTimeout(() => {
              callUrlHandler(url, context)
            }, 1000)
          } else {
            callUrlHandler(url, context)
          }
        }
      )
    }

    if (Iterable.savedConfig.customActionHandler) {
      RNEventEmitter.addListener(
        EventName.handleCustomActionCalled,
        (dict) => {
          const action = IterableAction.fromDict(dict["action"])
          const context = IterableActionContext.fromDict(dict["context"])
          Iterable.savedConfig.customActionHandler!(action, context)
        }
      )
    }

    if (Iterable.savedConfig.inAppHandler) {
      RNEventEmitter.addListener(
        EventName.handleInAppCalled,
        (messageDict) => {
          const message = IterableInAppMessage.fromDict(messageDict)
          const result = Iterable.savedConfig.inAppHandler!(message)
          RNIterableAPI.setInAppShowResponse(result)
        }
      )
    }

    if (Iterable.savedConfig.authHandler) {
      RNEventEmitter.addListener(
        EventName.handleAuthCalled,
        () => {
          Iterable.savedConfig.authHandler!()
            .then(authToken => {
              RNIterableAPI.passAlongAuthToken(authToken)
            })
        }
      )
    }

    function callUrlHandler(url: any, context: IterableActionContext) {
      if (Iterable.savedConfig.urlHandler!(url, context) == false) {
        Linking.canOpenURL(url)
          .then(canOpen => {
            if (canOpen) { Linking.openURL(url) }
          })
          .catch(reason => { Iterable.logger.log("could not open url: " + reason) })
      }
    }
  }
Example #23
Source File: markdown.tsx    From protect-scotland with Apache License 2.0 5 votes vote down vote up
MarkdownLink = (
  href: string,
  title: string,
  children: any,
  key: string,
  navigation: any,
  screenReaderEnabled: boolean,
  hasAccessibleLink: boolean
) => {
  const isHttp = href.startsWith('http');
  const isTel = href.startsWith('tel');

  // Markdown titles like [text](http://site.com "Title here") will be overridden by default accessibility labels

  if (isHttp || isTel) {
    const handle = isTel
      ? () => {
          const crossPlatformTarget = href.replace(/:(?=\d|\+)/, '://');
          Linking.openURL(crossPlatformTarget);
        }
      : () => openBrowserAsync(href);

    return screenReaderEnabled && !hasAccessibleLink ? (
      // we can't use TouchableWithoutFeedback because is not selectable by keyboard tab navigation
      <TouchableOpacity
        key={key}
        activeOpacity={1}
        accessible={true}
        accessibilityRole="link"
        accessibilityHint={title}
        accessibilityLabel={childrenAsText(children)}
        onPress={handle}>
        <Text>{children}</Text>
      </TouchableOpacity>
    ) : (
      <Text
        key={key}
        accessible={true}
        accessibilityRole="link"
        accessibilityHint={title}
        onPress={handle}>
        {children}
      </Text>
    );
  }

  return (
    <Button type="link" onPress={() => navigation.navigate(href)} label={title}>
      {children}
    </Button>
  );
}
Example #24
Source File: reservesLibWelcome.tsx    From THUInfo with MIT License 5 votes vote down vote up
ReservesLibWelcomeScreen = (props: {navigation: RootNav}) => {
	const themeName = useColorScheme();
	const {colors} = themes(themeName);

	const [search, setSearch] = useState("");

	useEffect(() => {
		check(PERMISSIONS.ANDROID.WRITE_EXTERNAL_STORAGE).then((r) => {
			if (r === RESULTS.DENIED) {
				request(PERMISSIONS.ANDROID.WRITE_EXTERNAL_STORAGE);
			}
		});
	}, []);

	return paginatedRefreshListScreen(
		async (_: PropsWithChildren<{navigation: RootNav}>, page) =>
			search.length === 0
				? []
				: (await helper.searchReservesLib(search, page)).data,
		(book, _, {navigation}) => (
			<BookItem
				book={book}
				onPress={() => navigation.navigate("ReservesLibPDF", {book})}
			/>
		),
		({bookId}) => bookId,
		undefined,
		(_, refresh) => (
			<View style={{paddingVertical: 8, paddingHorizontal: 12}}>
				<View
					style={{
						flexDirection: "row",
						alignItems: "center",
						justifyContent: "space-between",
					}}>
					<TextInput
						style={{
							fontSize: 15,
							flex: 1,
							backgroundColor: colors.themeBackground,
							color: colors.text,
							textAlign: "left",
							borderColor: "lightgrey",
							borderWidth: 1,
							borderRadius: 5,
							padding: 6,
						}}
						placeholder={getStr("search")}
						value={search}
						onChangeText={setSearch}
					/>
					<TouchableOpacity
						onPress={refresh}
						style={{padding: 6, paddingLeft: 12}}>
						<Icon name="search" size={20} color={colors.text} />
					</TouchableOpacity>
				</View>
				<TouchableOpacity
					style={{marginVertical: 8}}
					onPress={() =>
						Linking.openURL("https://github.com/ayf19").then(() =>
							console.log("Opening ayf19 GitHub page in system explorer"),
						)
					}>
					<Text style={{color: colors.primaryLight}}>作者:ayf19 @ GitHub</Text>
				</TouchableOpacity>
			</View>
		),
	)(props);
}
Example #25
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 #26
Source File: auth.ts    From solid-health with MIT License 5 votes vote down vote up
export function logIn(): Promise<void> {
  return Linking.openURL('https://jasonpaulos.github.io/solid-health/#appLogin');
}
Example #27
Source File: index.tsx    From nlw-ecoleta with MIT License 5 votes vote down vote up
Detail = () => {
    const [data, setData] = useState<Data>({} as Data);
    const navigation = useNavigation();
    const route = useRoute();

    const routeParams = route.params as Params;

    useEffect(() => {
      api.get(`points/${routeParams.point_id}`).then(response => {
        setData(response.data);
      });
    }, []);

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

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

    function handleWhatsapp() {
        Linking.openURL(`whatsapp://send?phone${data.point.whatsapp}$textTEnho interesse sobre 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={handleNavigateComposeMail}>
            <Icon name="mail" size={20} color="#FFF" />
            <Text style={styles.buttonText}>E-mail</Text>
          </RectButton>
        </View>
        </SafeAreaView>
    );
}
Example #28
Source File: ErrorDisplay.tsx    From expo-images-picker with MIT License 5 votes vote down vote up
ErrorDisplay = ({
    errorType,
    errorMessages,
    errorTextColor,
}: ErrorTypes) => {
    if (!errorType) return <Container />
    return (
        <Container>
            {errorType === 'hasNoAssets' && (
                <PermissionsError>
                    <Text color={errorTextColor || 'black'}>
                        {errorMessages?.hasNoAssets ||
                            'There are no assets to display.'}
                    </Text>
                </PermissionsError>
            )}

            {errorType === 'hasErrorWithPermissions' && (
                <PermissionsError>
                    <Text color={errorTextColor || 'black'}>
                        {errorMessages?.hasErrorWithPermissions ||
                            'Please Allow media and files permissions and try again.'}
                    </Text>
                    <Button
                        title="Open Settings"
                        onPress={() => {
                            Linking.openSettings()
                        }}
                    />
                </PermissionsError>
            )}
            {errorType === 'hasErrorWithLoading' && (
                <LoadingAssetsError>
                    <Text color={errorTextColor || 'black'}>
                        {errorMessages?.hasErrorWithLoading ||
                            'There was an error loading assets.'}
                    </Text>
                </LoadingAssetsError>
            )}
            {errorType === 'hasErrorWithResizing' && (
                <ResizeImagesError>
                    <Text color={errorTextColor || 'black'}>
                        {errorMessages?.hasErrorWithResizing ||
                            'There was an error resize assets.'}
                    </Text>
                </ResizeImagesError>
            )}
        </Container>
    )
}
Example #29
Source File: SelectInstanceHelp.tsx    From orangehrm-os-mobile with GNU General Public License v3.0 5 votes vote down vote up
onPressLearnMore = () => {
    Linking.canOpenURL(SUPPORT_URL).then((supported) => {
      if (supported) {
        Linking.openURL(SUPPORT_URL);
      }
    });
  };