react-native#Switch TypeScript Examples

The following examples show how to use react-native#Switch. 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: SwitchWithLabel.tsx    From natds-rn with ISC License 6 votes vote down vote up
SwitchWithLabelComponent = ({
  onChange, isLast, label, isActive, theme
}) => {
  const colorProps = {
    // eslint-disable-next-line @typescript-eslint/camelcase
    ios_backgroundColor: '#3e3e3e',
    thumbColor: getColorOnSuccess(theme),
    trackColor: {
      false: getColorLowEmphasis(theme) || '#eaeaea',
      true: getColorSuccess(theme) || '#BEC950'
    }
  }

  return (
    <SwitchContainer isLast={isLast}>
      <TextWithTheme style={{ paddingRight: 5 }}>{label}</TextWithTheme>
      <Switch {...colorProps} onValueChange={onChange} value={isActive} />
    </SwitchContainer>
  )
}
Example #2
Source File: CardRowSwitch.tsx    From react-native-ios-context-menu with MIT License 6 votes vote down vote up
/**
 * ```
 * ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐
 *   Title               ┌──┬─┐   
 * │ Subtitle            └──┴─┘  │
 *  ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ 
 * ```
 */                               
export function CardRowSwitch(props: {
  title: string;
  subtitle?: string;
  value: boolean;
  onValueChange: (value: boolean) => void;
}){
  return(
    <View style={styles.cardRowSwitchContainer}>
      <View style={styles.cardRowSwitchLabelContainer}>
        <Text style={styles.cardRowSwitchLabelText}>
          {props.title ?? 'title'}
        </Text>
        <Text style={styles.cardRowSwitchSubtitleText}>
          {props.subtitle ?? 'Toggle the value'}
        </Text>
      </View>
      <Switch
        value={props.value ?? false}
        onValueChange={props.onValueChange}
        trackColor={{
          true: Colors.PURPLE.A700,
          false: Colors.PURPLE.A100
        }}
      />
    </View>
  );
}
Example #3
Source File: NotificationRow.tsx    From nyxo-app with GNU General Public License v3.0 6 votes vote down vote up
NotificationRow = (props: NotificationDataItemProps) => {
  const onValueChange = (value: boolean) => {
    props.pressSwitch(props.actionType, value)
  }
  return (
    <Wrapper>
      <Container>
        <P>{props.title}</P>
        <Switch value={props.enabled} onValueChange={onValueChange} />
      </Container>
    </Wrapper>
  )
}
Example #4
Source File: items.tsx    From THUInfo with MIT License 5 votes vote down vote up
SettingsSwitch = ({
	textOn,
	textOff,
	onValueChange,
	defaultValue,
	iconOn,
	iconOff,
}: {
	textOn: string;
	textOff: string;
	onValueChange: (state: boolean) => void;
	defaultValue: boolean;
	iconOn: ReactElement | undefined;
	iconOff: ReactElement | undefined;
}) => {
	const themeName = useColorScheme();
	const {colors} = themes(themeName);
	const [status, setStatus] = useState(defaultValue);
	return (
		<View
			style={{
				padding: 8,
				flexDirection: "row",
				justifyContent: "space-between",
			}}>
			<View style={{flexDirection: "row", alignItems: "center", flex: 1}}>
				{setIconWidth(status ? iconOn : iconOff, colors)}
				<Text style={{fontSize: 17, marginHorizontal: 10, color: colors.text}}>
					{status ? textOn : textOff}
				</Text>
			</View>
			<Switch
				style={{flex: 0}}
				value={status}
				onValueChange={(value) => {
					setStatus(value);
					onValueChange(value);
				}}
			/>
		</View>
	);
}
Example #5
Source File: Toggle.tsx    From swiftui-react-native with MIT License 5 votes vote down vote up
Toggle: React.FC<ToggleProps> = ({
  isOn,
  tint,
  padding,
  backgroundColor,
  shadow,
  frame,
  border,
  opacity,
  zIndex,
  cornerRadius,
  rotationEffect,
  scaleEffect,
  style,
  alert,
  onAppear,
  onDisappear,
  onChange,
}) => {
  useAlert(alert);
  useLifecycle(onAppear, onDisappear);
  const colorScheme = useColorScheme();

  return (
    <Switch
      style={[
        {
          opacity,
          zIndex,
          backgroundColor: getColor(backgroundColor, colorScheme),
          ...getCornerRadius(cornerRadius),
          ...getPadding(padding),
          ...getFrame(frame),
          ...getBorder(border),
          ...getShadow(shadow),
          ...getTransform(scaleEffect, rotationEffect),
        },
        style,
      ]}
      value={isOn.value}
      onValueChange={() => {
        const newValue = !isOn.value;
        isOn.setValue(newValue);
        if (onChange) {
          onChange(newValue);
        }
      }}
      trackColor={{ true: getColor(tint, colorScheme), false: null }}
    />
  );
}
Example #6
Source File: ContactTracer.tsx    From SQUID with MIT License 5 votes vote down vote up
render() {
    return (
      <MyBackground variant="light">
        <StatusBar
          barStyle="dark-content"
          backgroundColor={COLORS.PRIMARY_LIGHT}
        />
        <SafeAreaView style={{ flex: 1 }}>
          <View>
            <View style={styles.body}>
              <View>
                <Text style={styles.mediumText}>
                  User ID: {this.state.userId}
                </Text>
              </View>
              <View style={styles.horizontalRow}>
                <Text style={styles.normalText}>Service: </Text>
                <Switch
                  trackColor={{ false: '#767577', true: '#81b0ff' }}
                  thumbColor={
                    this.state.isServiceEnabled ? '#f5dd4b' : '#f4f3f4'
                  }
                  ios_backgroundColor="#3e3e3e"
                  onValueChange={this.onServiceSwitchChanged}
                  value={this.state.isServiceEnabled}
                  disabled={
                    !this.state.isLocationPermissionGranted ||
                    !this.state.isBluetoothOn
                  }
                />
              </View>
              <ScrollView
                contentInsetAdjustmentBehavior="automatic"
                style={styles.scrollView}
              >
                <Text>{this.state.statusText}</Text>
              </ScrollView>
            </View>
          </View>
        </SafeAreaView>
      </MyBackground>
    )
  }
Example #7
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 #8
Source File: ActionButton.tsx    From react-native-crypto-wallet-app with MIT License 5 votes vote down vote up
ActionButton: React.FC<IActionButtonProps> = ({
  label,
  icon,
  info,
  isToggle = false,
  toggleValue,
  onPress,
  onToggle,
}) => {
  const theme = useTheme<Theme>();

  const handlePress = () => {
    if (isToggle && onToggle) {
      onToggle(!toggleValue);
    } else {
      onPress && onPress();
    }
  };

  return (
    <ButtonContainer
      onPress={handlePress}
      backgroundColor="lightBlue"
      justifyContent="space-between"
    >
      <Box flexDirection="row" alignItems="center">
        {icon && <Icon name={icon} color="label" />}
        <StyledText variant="sublimeSemiBold" color="titleHeadline" style={ActionButtonStyle.label}>
          {label}
        </StyledText>
      </Box>
      {isToggle && (
        <Switch
          onValueChange={onToggle}
          value={toggleValue}
          thumbColor="white"
          trackColor={{
            true: theme.colors.success,
            false: theme.colors.disabled,
          }}
        />
      )}
      {!isToggle && (
        <Box flexDirection="row" alignItems="center">
          {info && (
            <StyledText variant="paragraph" color="titleHeadline" style={ActionButtonStyle.info}>
              {info}
            </StyledText>
          )}
          <Icon name="arrowRight" color="label" />
        </Box>
      )}
    </ButtonContainer>
  );
}
Example #9
Source File: about.tsx    From beancount-mobile with MIT License 4 votes vote down vote up
About = connect(
  (state: AppState) => ({
    authToken: state.base.authToken,
    locale: state.base.locale,
    currentTheme: state.base.currentTheme,
    userId: state.base.userId,
  }),
  (dispatch) => ({
    logout(authToken: string): void {
      dispatch(actionLogout(authToken));
    },
    updateReduxState(payload: { base: { locale: string } }): void {
      dispatch(actionUpdateReduxState(payload));
    },
  })
)(
  ({
    authToken,
    locale,
    logout,
    updateReduxState,
    currentTheme,
    userId,
    navigation,
  }: Props) => {
    const theme = useTheme().colorTheme;
    const { setLocale } = React.useContext(LocalizationContext);
    const pickerSource = [
      { value: ReportStatus.WEEKLY, label: i18n.t("weekly") },
      { value: ReportStatus.MONTHLY, label: i18n.t("monthly") },
      { value: ReportStatus.OFF, label: i18n.t("off") },
    ];

    useEffect(() => {
      async function init() {
        await registerForPushNotificationAsync();
      }
      init();
    }, []);

    const [reportAnimateCount, setReportAnimateCount] = useState(0);
    const [subscriptionFlash, setSubscriptionFlash] = useState(false);
    const isFocused = useIsFocused();

    React.useEffect(() => {
      async function init() {
        try {
          const value = await AsyncStorage.getItem("@SubscriptionFlash:key");
          if (value !== null) {
            setSubscriptionFlash(value === "true");
          } else {
            setSubscriptionFlash(false);
          }
          await AsyncStorage.setItem("@SubscriptionFlash:key", "false");
        } catch (error) {
          console.error(`failed to get subscription flash value: ${error}`);
        }
      }
      init();
    }, [isFocused]);

    useEffect(() => {
      if (subscriptionFlash) {
        const interval = setInterval(() => {
          if (reportAnimateCount < 5) {
            setReportAnimateCount(reportAnimateCount + 1);
          }
        }, 300);
        return () => clearInterval(interval);
      }
      setReportAnimateCount(0);
      return undefined;
    }, [subscriptionFlash, reportAnimateCount]);

    const { emailReportStatus } = useUserProfile(userId);
    const [reportStatus, setReportStatue] = useState<string>(
      emailReportStatus ? emailReportStatus.toString() : ""
    );

    useEffect(() => {
      setReportStatue(emailReportStatus ? emailReportStatus.toString() : "");
    }, [emailReportStatus]);

    const { error, mutate } = useUpdateReportSubscribeToRemote();

    const getReportStatusLabel = (status: string) => {
      switch (status) {
        case ReportStatus.OFF:
          return i18n.t("off");
        case ReportStatus.WEEKLY:
          return i18n.t("weekly");
        case ReportStatus.MONTHLY:
          return i18n.t("monthly");
        default:
          return i18n.t("off");
      }
    };

    const getReportStatusEnum = (status: string) => {
      switch (status) {
        case ReportStatus.OFF:
          return ReportStatus.OFF;
        case ReportStatus.WEEKLY:
          return ReportStatus.WEEKLY;
        case ReportStatus.MONTHLY:
          return ReportStatus.MONTHLY;
        default:
          return ReportStatus.OFF;
      }
    };

    const renderAppSection = () => {
      const backgroundColor = {
        backgroundColor: theme.white,
        color: theme.text01,
      };

      const { spendingReportSubscription } = useFeatureFlags(userId);

      return (
        // @ts-ignore
        <List
          style={backgroundColor}
          renderHeader={<ListHeader>{i18n.t("about")}</ListHeader>}
        >
          <Item
            disabled
            extra={Platform.OS === "ios" ? "Apple Store" : "Google Play"}
            arrow="horizontal"
            style={backgroundColor}
            onPress={async () => {
              const storeUrl =
                Platform.OS === "ios"
                  ? "https://apps.apple.com/us/app/id1527950512"
                  : "https://play.google.com/store/apps/details?id=io.beancount.android";
              if (storeUrl) {
                await WebBrowser.openBrowserAsync(storeUrl);
                await analytics.track("tap_review_app", { storeUrl });
              }
            }}
          >
            {i18n.t("reviewApp")}
          </Item>

          {spendingReportSubscription && (
            <Picker
              data={pickerSource}
              cols={1}
              extra={getReportStatusLabel(reportStatus)}
              onChange={async (value) => {
                const newValue = value ? String(value[0]) : "";
                if (newValue === reportStatus) {
                  return;
                }
                setReportStatue(newValue);
                const loadingKey = Toast.loading(i18n.t("updating"));
                await mutate({
                  variables: { userId, status: getReportStatusEnum(newValue) },
                });
                Portal.remove(loadingKey);
                if (!error) {
                  Toast.success(i18n.t("updateSuccess"));
                } else {
                  console.error("failed to update report status", error);
                  Toast.fail(i18n.t("updateFailed"));
                }
              }}
            >
              <Item
                style={[
                  backgroundColor,
                  {
                    backgroundColor:
                      reportAnimateCount % 2 === 1
                        ? theme.warning
                        : theme.white,
                  },
                ]}
                arrow="horizontal"
              >
                {i18n.t("subscribe")}
              </Item>
            </Picker>
          )}

          <Item
            disabled
            style={backgroundColor}
            extra={
              <Switch
                value={String(locale).startsWith("en")}
                onValueChange={async (value) => {
                  const changeTo = value ? "en" : "zh";
                  updateReduxState({
                    base: { locale: changeTo },
                  });
                  i18n.locale = changeTo;
                  setLocale(changeTo);
                  await analytics.track("tap_switch_language", { changeTo });
                }}
              />
            }
          >
            {i18n.t("currentLanguage")}
            <Brief>
              {String(locale).startsWith("en")
                ? i18n.t("english")
                : i18n.t("chinese")}
            </Brief>
          </Item>

          <Item
            style={backgroundColor}
            disabled
            extra={
              <Switch
                value={currentTheme === "dark"}
                onValueChange={async (value) => {
                  const mode = value ? "dark" : "light";
                  updateReduxState({
                    base: { currentTheme: mode },
                  });
                  await analytics.track("tap_switch_theme", { mode });
                }}
              />
            }
          >
            {i18n.t("theme")}
            <Brief>{currentTheme === "dark" ? "Dark" : "Light"}</Brief>
          </Item>
          <Item
            style={backgroundColor}
            disabled
            extra={Constants.nativeAppVersion}
          >
            {i18n.t("currentVersion")}
          </Item>
          {authToken ? (
            <Item
              style={backgroundColor}
              disabled
              onPress={() => {
                Alert.alert(
                  "",
                  i18n.t("logoutAlertMsg"),
                  [
                    { text: i18n.t("logoutAlertCancel"), style: "cancel" },
                    {
                      text: i18n.t("logoutAlertConfirm"),
                      onPress: () => {
                        logout(authToken);
                      },
                    },
                  ],
                  { cancelable: false }
                );
              }}
            >
              {i18n.t("logout")}
            </Item>
          ) : (
            <View />
          )}
        </List>
      );
    };

    return (
      <ScrollView style={{ backgroundColor: theme.white }}>
        <AccountHeader />
        <InviteSection navigation={navigation} />
        {renderAppSection()}
      </ScrollView>
    );
  }
)
Example #10
Source File: App.tsx    From react-native-giphy-ui with MIT License 4 votes vote down vote up
export default function App() {
  const [gif, setGif] = useState<GiphyGif | undefined>();
  const [theme, setTheme] = useState<GiphyTheme>();
  const [rating, setRating] = useState<GiphyUIRating>('ratedPG');
  const [mediaTypes, setMediaTypes] = useState<GiphyMediaType[]>(['gifs']);
  const [shouldLocalizeSearch, setShouldLocalizeSearch] = useState(false);
  const [showConfirmationScreen, setShowConfirmationScreen] = useState(false);
  const [useNativeMediaView] = useState(false);

  const openGifPicker = useCallback(() => {
    setGif(undefined);
    GiphyUi.present(
      {
        mediaTypes,
        theme,
        rating,
        showConfirmationScreen,
        shouldLocalizeSearch,
      },
      setGif
    );
  }, [mediaTypes, theme, rating, showConfirmationScreen, shouldLocalizeSearch]);

  return (
    <>
      <ScrollView
        style={styles.container}
        contentContainerStyle={styles.content}
        contentInset={{ bottom: 500 }}
      >
        {gif && (
          <View style={styles.gif}>
            <Text style={styles.gifTitle}>
              Selected Gif {useNativeMediaView && '(Native View)'}
            </Text>
            {useNativeMediaView ? (
              <GiphyMediaView media={gif} />
            ) : (
              <Image
                source={{ uri: gif.images.downsized.url }}
                style={styles.gifImage}
              />
            )}
          </View>
        )}
        <View style={styles.settings}>
          <View style={styles.setting}>
            <Text style={styles.settingTitle}>Theme</Text>
            <Picker
              selectedValue={theme}
              onValueChange={value => setTheme(value)}
              style={styles.picker}
            >
              <Picker.Item label="Light" value="light" />
              <Picker.Item label="Dark" value="dark" />
            </Picker>
          </View>
          <View style={styles.setting}>
            <Text style={styles.settingTitle}>Media Types</Text>
            <Picker
              selectedValue={mediaTypes[0]}
              onValueChange={value => setMediaTypes([value])}
              style={styles.picker}
            >
              <Picker.Item label="Gifs" value="gifs" />
              <Picker.Item label="Emojis" value="emoji" />
              <Picker.Item label="Stickers" value="stickers" />
              <Picker.Item label="Text" value="text" />
            </Picker>
          </View>
          <View style={styles.setting}>
            <Text style={styles.settingTitle}>Rating</Text>
            <Picker
              selectedValue={rating}
              onValueChange={value => setRating(value)}
              style={styles.picker}
            >
              <Picker.Item label="PG" value="ratedPG" />
              <Picker.Item label="PG 13" value="ratedPG13" />
              <Picker.Item label="Unrated" value="unrated" />
              <Picker.Item label="Rated R" value="ratedR" />
              <Picker.Item label="Rated Y" value="ratedY" />
              <Picker.Item label="Rated G" value="ratedG" />
              <Picker.Item label="NSFW" value="nsfw" />
            </Picker>
          </View>
          {Platform.OS === 'ios' && (
            <>
              <View style={styles.settingRow}>
                <Text style={styles.settingTitle}>
                  Show Confirmation Screen
                </Text>
                <Switch
                  value={showConfirmationScreen}
                  onValueChange={setShowConfirmationScreen}
                />
              </View>
              <View style={styles.settingRow}>
                <Text style={styles.settingTitle}>Localize Search</Text>
                <Switch
                  value={shouldLocalizeSearch}
                  onValueChange={setShouldLocalizeSearch}
                />
              </View>
              {/* <View style={styles.settingRow}>
                <Text style={styles.settingTitle}>Use Native Media View</Text>
                <Switch
                  value={useNativeMediaView}
                  onValueChange={setUseNativeMediaView}
                />
              </View> */}
            </>
          )}
        </View>
      </ScrollView>
      <View style={styles.float}>
        <Button onPress={openGifPicker} title="Open Gif Picker" />
      </View>
    </>
  );
}
Example #11
Source File: App.tsx    From react-native-msal with MIT License 4 votes vote down vote up
export default function App() {
  const [authResult, setAuthResult] = React.useState<MSALResult | null>(null);
  const [iosEphemeralSession, setIosEphemeralSession] = React.useState(false);
  const webviewParameters: MSALWebviewParams = {
    ios_prefersEphemeralWebBrowserSession: iosEphemeralSession,
  };

  React.useEffect(() => {
    async function init() {
      try {
        await b2cClient.init();
        const isSignedIn = await b2cClient.isSignedIn();
        if (isSignedIn) {
          setAuthResult(await b2cClient.acquireTokenSilent({ scopes }));
        }
      } catch (error) {
        console.error(error);
      }
    }
    init();
  }, []);

  const handleSignInPress = async () => {
    try {
      const res = await b2cClient.signIn({ scopes, webviewParameters });
      setAuthResult(res);
    } catch (error) {
      console.warn(error);
    }
  };

  const handleAcquireTokenPress = async () => {
    try {
      const res = await b2cClient.acquireTokenSilent({ scopes, forceRefresh: true });
      setAuthResult(res);
    } catch (error) {
      console.warn(error);
    }
  };

  const handleSignoutPress = async () => {
    try {
      await b2cClient.signOut();
      setAuthResult(null);
    } catch (error) {
      console.warn(error);
    }
  };

  return (
    <SafeAreaView style={styles.container}>
      <View style={styles.buttonContainer}>
        {authResult ? (
          <>
            <TouchableOpacity style={styles.button} onPress={handleAcquireTokenPress}>
              <Text>Acquire Token (Silent)</Text>
            </TouchableOpacity>
            <TouchableOpacity style={styles.button} onPress={handleSignoutPress}>
              <Text>Sign Out</Text>
            </TouchableOpacity>
          </>
        ) : (
          <TouchableOpacity style={styles.button} onPress={handleSignInPress}>
            <Text>Sign In</Text>
          </TouchableOpacity>
        )}

        {Platform.OS === 'ios' && (
          <TouchableOpacity
            style={[styles.button, styles.switchButton]}
            onPress={() => setIosEphemeralSession(!iosEphemeralSession)}
          >
            <Text>Prefer ephemeral browser session (iOS only)</Text>
            <Switch value={iosEphemeralSession} onValueChange={setIosEphemeralSession} />
          </TouchableOpacity>
        )}
      </View>
      <ScrollView style={styles.scrollView}>
        <Text>{JSON.stringify(authResult, null, 2)}</Text>
      </ScrollView>
    </SafeAreaView>
  );
}
Example #12
Source File: BancontactPaymentScreen.tsx    From stripe-react-native with MIT License 4 votes vote down vote up
export default function BancontactPaymentScreen() {
  const [email, setEmail] = useState('');
  const [saveIban, setSaveIban] = useState(false);
  const { confirmPayment, loading } = useConfirmPayment();

  const fetchPaymentIntentClientSecret = async () => {
    const response = await fetch(`${API_URL}/create-payment-intent`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        email,
        currency: 'eur',
        items: [{ id: 'id' }],
        request_three_d_secure: 'any',
        payment_method_types: ['bancontact'],
      }),
    });
    const { clientSecret, error } = await response.json();

    return { clientSecret, error };
  };

  const handlePayPress = async () => {
    const { clientSecret, error: clientSecretError } =
      await fetchPaymentIntentClientSecret();

    if (clientSecretError) {
      Alert.alert(`Error`, clientSecretError);
      return;
    }

    const billingDetails: BillingDetails = {
      name: 'John Doe',
      email: '[email protected]',
    };

    const { error, paymentIntent } = await confirmPayment(
      clientSecret,
      {
        paymentMethodType: 'Bancontact',
        paymentMethodData: {
          billingDetails,
        },
      },
      { setupFutureUsage: saveIban ? 'OffSession' : undefined }
    );

    if (error) {
      Alert.alert(`Error code: ${error.code}`, error.message);
      console.log('Payment confirmation error', error.message);
    } else if (paymentIntent) {
      Alert.alert(
        'Success',
        `The payment was confirmed successfully! currency: ${paymentIntent.currency}`
      );
      console.log('Success from promise', paymentIntent);
    }
  };

  return (
    <PaymentScreen>
      <TextInput
        placeholder="E-mail"
        autoCapitalize="none"
        keyboardType="email-address"
        onChange={(value) => setEmail(value.nativeEvent.text)}
        style={styles.input}
      />

      <Button
        variant="primary"
        onPress={handlePayPress}
        title="Pay"
        accessibilityLabel="Pay"
        loading={loading}
      />
      <View style={styles.row}>
        <Switch
          onValueChange={(value) => setSaveIban(value)}
          value={saveIban}
        />
        <Text style={styles.text}>Save IBAN during payment</Text>
      </View>
    </PaymentScreen>
  );
}
Example #13
Source File: IdealPaymentScreen.tsx    From stripe-react-native with MIT License 4 votes vote down vote up
export default function IdealPaymentScreen() {
  const [email, setEmail] = useState('');
  const { confirmPayment, loading } = useConfirmPayment();
  const [bankName, setBankName] = useState<string | undefined>();
  const [saveIban, setSaveIban] = useState(false);

  const fetchPaymentIntentClientSecret = async () => {
    const response = await fetch(`${API_URL}/create-payment-intent`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        email,
        currency: 'eur',
        items: [{ id: 'id' }],
        request_three_d_secure: 'any',
        payment_method_types: ['ideal'],
      }),
    });
    const { clientSecret, error } = await response.json();

    return { clientSecret, error };
  };

  const handlePayPress = async () => {
    const { clientSecret, error: clientSecretError } =
      await fetchPaymentIntentClientSecret();

    if (clientSecretError) {
      Alert.alert(`Error`, clientSecretError);
      return;
    }

    const billingDetails: BillingDetails = {
      name: 'John Doe',
      email: '[email protected]',
    };

    const { error, paymentIntent } = await confirmPayment(
      clientSecret,
      {
        paymentMethodType: 'Ideal',
        paymentMethodData: {
          billingDetails,
          bankName,
        },
      },
      { setupFutureUsage: saveIban ? 'OffSession' : undefined }
    );

    if (error) {
      Alert.alert(`Error code: ${error.code}`, error.message);
      console.log('Payment confirmation error', error.message);
    } else if (paymentIntent) {
      Alert.alert(
        'Success',
        `The payment was confirmed successfully! currency: ${paymentIntent.currency}`
      );
      console.log('Success from promise', paymentIntent);
    }
  };

  return (
    <PaymentScreen>
      <TextInput
        autoCapitalize="none"
        placeholder="E-mail"
        keyboardType="email-address"
        onChange={(value) => setEmail(value.nativeEvent.text)}
        style={styles.input}
      />
      <Picker
        selectedValue={bankName}
        onValueChange={(itemValue) => setBankName(itemValue)}
      >
        <Picker.Item label="Optional - choose your bank" />
        <Picker.Item label="ABN Amro" value="abn_amro" />
        <Picker.Item label="ASN Bank" value="asn_bank" />
        <Picker.Item label="bunq B.V." value="bunq" />
        <Picker.Item label="Handelsbanken" value="handelsbanken" />
        <Picker.Item label="ING Bank" value="ing" />
        <Picker.Item label="Knab" value="knab" />
        <Picker.Item label="Moneyou" value="moneyou" />
        <Picker.Item label="Rabobank" value="rabobank" />
        <Picker.Item label="Regiobank" value="regiobank" />
        <Picker.Item label="Revolut" value="revolut" />
        <Picker.Item label="SNS Bank" value="sns_bank" />
        <Picker.Item label="Triodos Bank" value="triodos_bank" />
        <Picker.Item label="Van Lanschot" value="van_lanschot" />
      </Picker>
      <Button
        variant="primary"
        onPress={handlePayPress}
        title="Pay"
        accessibilityLabel="Pay"
        loading={loading}
      />
      <View style={styles.row}>
        <Switch
          onValueChange={(value) => setSaveIban(value)}
          value={saveIban}
        />
        <Text style={styles.text}>Save IBAN during payment</Text>
      </View>
    </PaymentScreen>
  );
}
Example #14
Source File: MultilineWebhookPaymentScreen.tsx    From stripe-react-native with MIT License 4 votes vote down vote up
export default function MultilineWebhookPaymentScreen() {
  const [email, setEmail] = useState('');
  const [saveCard, setSaveCard] = useState(false);
  const [isComplete, setComplete] = useState(false);

  const { confirmPayment, loading } = useConfirmPayment();

  const fetchPaymentIntentClientSecret = async () => {
    const response = await fetch(`${API_URL}/create-payment-intent`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        email,
        currency: 'usd',
        items: [{ id: 'id' }],
        // request_three_d_secure: 'any',
      }),
    });
    const { clientSecret } = await response.json();

    return clientSecret;
  };

  const handlePayPress = async () => {
    // 1. fetch Intent Client Secret from backend
    const clientSecret = await fetchPaymentIntentClientSecret();

    // 2. Gather customer billing information (ex. email)
    const billingDetails: BillingDetails = {
      email: '[email protected]',
      phone: '+48888000888',
      address: {
        city: 'Houston',
        country: 'US',
        line1: '1459  Circle Drive',
        line2: 'Texas',
        postalCode: '77063',
      },
    }; // mocked data for tests

    // 3. Confirm payment with card details
    // The rest will be done automatically using webhooks
    const { error, paymentIntent } = await confirmPayment(
      clientSecret,
      {
        paymentMethodType: 'Card',
        paymentMethodData: { billingDetails },
      },
      { setupFutureUsage: saveCard ? 'OffSession' : undefined }
    );

    if (error) {
      Alert.alert(`Error code: ${error.code}`, error.message);
      console.log('Payment confirmation error', error.message);
    } else if (paymentIntent) {
      Alert.alert(
        'Success',
        `The payment was confirmed successfully! currency: ${paymentIntent.currency}`
      );
      console.log('Success from promise', paymentIntent);
    }
  };

  return (
    <PaymentScreen>
      <TextInput
        autoCapitalize="none"
        placeholder="E-mail"
        keyboardType="email-address"
        onChange={(value) => setEmail(value.nativeEvent.text)}
        style={styles.input}
      />
      <CardForm
        placeholders={{
          number: '4242 4242 4242 4242',
          postalCode: '12345',
          cvc: 'CVC',
          expiration: 'MM|YY',
        }}
        autofocus
        cardStyle={inputStyles}
        style={styles.cardField}
        onFormComplete={(cardDetails) => {
          console.log(cardDetails);
          setComplete(cardDetails.complete);
        }}
      />
      <View style={styles.row}>
        <Switch
          onValueChange={(value) => setSaveCard(value)}
          value={saveCard}
        />
        <Text style={styles.text}>Save card during payment</Text>
      </View>
      <Button
        variant="primary"
        onPress={handlePayPress}
        title="Pay"
        accessibilityLabel="Pay"
        disabled={!isComplete}
        loading={loading}
      />
    </PaymentScreen>
  );
}
Example #15
Source File: SepaPaymentScreen.tsx    From stripe-react-native with MIT License 4 votes vote down vote up
export default function SepaPaymentScreen() {
  const [email, setEmail] = useState('');
  const { confirmPayment, loading } = useConfirmPayment();
  const [iban, setIban] = useState('');
  const [saveIban, setSaveIban] = useState(false);

  const fetchPaymentIntentClientSecret = async () => {
    const response = await fetch(`${API_URL}/create-payment-intent`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        email,
        currency: 'eur',
        items: [{ id: 'id' }],
        payment_method_types: ['sepa_debit'],
      }),
    });
    const { clientSecret, error } = await response.json();

    return { clientSecret, error };
  };

  const handlePayPress = async () => {
    const { clientSecret, error: clientSecretError } =
      await fetchPaymentIntentClientSecret();

    if (clientSecretError) {
      Alert.alert(`Error`, clientSecretError);
      return;
    }

    const billingDetails: BillingDetails = {
      name: 'John Doe',
      email: email,
    };

    const { error, paymentIntent } = await confirmPayment(
      clientSecret,
      {
        paymentMethodType: 'SepaDebit',
        paymentMethodData: { billingDetails, iban },
      },
      { setupFutureUsage: saveIban ? 'OffSession' : undefined }
    );

    if (error) {
      Alert.alert(`Error code: ${error.code}`, error.message);
    } else if (paymentIntent) {
      if (paymentIntent.status === PaymentIntent.Status.Processing) {
        Alert.alert(
          'Processing',
          `The debit has been successfully submitted and is now processing.`
        );
      } else if (paymentIntent.status === PaymentIntent.Status.Succeeded) {
        Alert.alert(
          'Success',
          `The payment was confirmed successfully! currency: ${paymentIntent.currency}`
        );
      } else {
        Alert.alert('Payment status:', paymentIntent.status);
      }
    }
  };

  return (
    <PaymentScreen>
      <TextInput
        autoCapitalize="none"
        placeholder="E-mail"
        keyboardType="email-address"
        onChange={(value) => setEmail(value.nativeEvent.text)}
        style={styles.input}
      />
      <TextInput
        autoCapitalize="characters"
        placeholder="Iban"
        onChange={(value) => setIban(value.nativeEvent.text.toLowerCase())}
        style={styles.input}
      />
      <Button
        variant="primary"
        onPress={handlePayPress}
        title="Pay"
        accessibilityLabel="Pay"
        loading={loading}
      />
      <View style={styles.row}>
        <Switch
          onValueChange={(value) => setSaveIban(value)}
          value={saveIban}
        />
        <Text style={styles.text}>Save IBAN during payment</Text>
      </View>
    </PaymentScreen>
  );
}
Example #16
Source File: SofortPaymentScreen.tsx    From stripe-react-native with MIT License 4 votes vote down vote up
export default function SofortPaymentScreen() {
  const [email, setEmail] = useState('');
  const [saveIban, setSaveIban] = useState(false);
  const { confirmPayment, loading } = useConfirmPayment();

  const fetchPaymentIntentClientSecret = async () => {
    const response = await fetch(`${API_URL}/create-payment-intent`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        email,
        currency: 'eur',
        items: [{ id: 'id' }],
        payment_method_types: ['sofort'],
      }),
    });
    const { clientSecret, error } = await response.json();

    return { clientSecret, error };
  };

  const handlePayPress = async () => {
    const { clientSecret, error: clientSecretError } =
      await fetchPaymentIntentClientSecret();

    if (clientSecretError) {
      Alert.alert(`Error`, clientSecretError);
      return;
    }

    const billingDetails: BillingDetails = {
      name: 'John Doe',
      email: '[email protected]',
    };

    const { error, paymentIntent } = await confirmPayment(
      clientSecret,
      {
        paymentMethodType: 'Sofort',
        paymentMethodData: {
          billingDetails,
          country: 'DE',
        },
      },
      { setupFutureUsage: saveIban ? 'OffSession' : undefined }
    );

    if (error) {
      Alert.alert(`Error code: ${error.code}`, error.message);
      console.log('Payment confirmation error', error.message);
    } else if (paymentIntent) {
      if (paymentIntent.status === PaymentIntent.Status.Processing) {
        Alert.alert('Processing', `The paymentIntent is processing`);
      } else {
        Alert.alert(
          'Success',
          `The payment was confirmed successfully! currency: ${paymentIntent.currency}`
        );
      }
    }
  };

  return (
    <PaymentScreen>
      <TextInput
        autoCapitalize="none"
        placeholder="E-mail"
        keyboardType="email-address"
        onChange={(value) => setEmail(value.nativeEvent.text)}
        style={styles.input}
      />

      <Button
        variant="primary"
        onPress={handlePayPress}
        title="Pay"
        accessibilityLabel="Pay"
        loading={loading}
      />
      <View style={styles.row}>
        <Switch
          onValueChange={(value) => setSaveIban(value)}
          value={saveIban}
        />
        <Text style={styles.text}>Save IBAN during payment</Text>
      </View>
    </PaymentScreen>
  );
}
Example #17
Source File: WebhookPaymentScreen.tsx    From stripe-react-native with MIT License 4 votes vote down vote up
export default function WebhookPaymentScreen() {
  const [email, setEmail] = useState('');
  const [saveCard, setSaveCard] = useState(false);

  const { confirmPayment, loading } = useConfirmPayment();

  const fetchPaymentIntentClientSecret = async () => {
    const response = await fetch(`${API_URL}/create-payment-intent`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        email,
        currency: 'usd',
        items: [{ id: 'id' }],
        // request_three_d_secure: 'any',
      }),
    });
    const { clientSecret } = await response.json();

    return clientSecret;
  };

  const handlePayPress = async () => {
    // 1. fetch Intent Client Secret from backend
    const clientSecret = await fetchPaymentIntentClientSecret();

    // 2. Gather customer billing information (ex. email)
    const billingDetails: BillingDetails = {
      email: '[email protected]',
      phone: '+48888000888',
      address: {
        city: 'Houston',
        country: 'US',
        line1: '1459  Circle Drive',
        line2: 'Texas',
        postalCode: '77063',
      },
    }; // mocked data for tests

    // 3. Confirm payment with card details
    // The rest will be done automatically using webhooks
    const { error, paymentIntent } = await confirmPayment(
      clientSecret,
      {
        paymentMethodType: 'Card',
        paymentMethodData: {
          billingDetails,
        },
      },
      {
        setupFutureUsage: saveCard ? 'OffSession' : undefined,
      }
    );

    if (error) {
      Alert.alert(`Error code: ${error.code}`, error.message);
      console.log('Payment confirmation error', error.message);
    } else if (paymentIntent) {
      Alert.alert(
        'Success',
        `The payment was confirmed successfully! currency: ${paymentIntent.currency}`
      );
      console.log('Success from promise', paymentIntent);
    }
  };

  return (
    <PaymentScreen>
      <TextInput
        autoCapitalize="none"
        placeholder="E-mail"
        keyboardType="email-address"
        onChange={(value) => setEmail(value.nativeEvent.text)}
        style={styles.input}
      />
      <CardField
        postalCodeEnabled={false}
        autofocus
        placeholders={{
          number: '4242 4242 4242 4242',
          postalCode: '12345',
          cvc: 'CVC',
          expiration: 'MM|YY',
        }}
        onCardChange={(cardDetails) => {
          console.log('cardDetails', cardDetails);
        }}
        onFocus={(focusedField) => {
          console.log('focusField', focusedField);
        }}
        cardStyle={inputStyles}
        style={styles.cardField}
      />
      <View style={styles.row}>
        <Switch
          onValueChange={(value) => setSaveCard(value)}
          value={saveCard}
        />
        <Text style={styles.text}>Save card during payment</Text>
      </View>
      <Button
        variant="primary"
        onPress={handlePayPress}
        title="Pay"
        accessibilityLabel="Pay"
        loading={loading}
      />
    </PaymentScreen>
  );
}
Example #18
Source File: OrphanageData.tsx    From nlw-03-omnistack with MIT License 4 votes vote down vote up
export default function OrphanageData() {
  const route = useRoute();
  const navigation = useNavigation();

  const [open_on_weekends, setOpenOnWeekends] = useState(false);

  const params = route.params as OrphanageDataRouteParams;
  const position = params.position;

  function handleCreateOrphanage() {
    // todo
  }

  async function handleSelectImages() {
    const { status } = await ImagePicker.requestCameraRollPermissionsAsync();

    if (status !== 'granted') {
      alert('Eita! Precisamos de acesso às suas fotos...');
    }

    const result = await ImagePicker.launchImageLibraryAsync({
      allowsEditing: true,
      quality: 1,
    });

    console.log(result);
  }

  return (
    <ScrollView style={styles.container} contentContainerStyle={{ padding: 24 }}>
      <Text style={styles.title}>Dados</Text>

      <Text style={styles.label}>Nome</Text>
      <TextInput
        style={styles.input}
      />

      <Text style={styles.label}>Sobre</Text>
      <TextInput
        style={[styles.input, { height: 110 }]}
        multiline
      />

      <Text style={styles.label}>Whatsapp</Text>
      <TextInput
        style={styles.input}
      />

      <Text style={styles.label}>Fotos</Text>
      <TouchableOpacity style={styles.imagesInput} onPress={handleSelectImages}>
        <Feather name="plus" size={24} color="#15B6D6" />
      </TouchableOpacity>

      <Text style={styles.title}>Visitação</Text>

      <Text style={styles.label}>Instruções</Text>
      <TextInput
        style={[styles.input, { height: 110 }]}
        multiline
      />

      <Text style={styles.label}>Horario de visitas</Text>
      <TextInput
        style={styles.input}
      />

      <View style={styles.switchContainer}>
        <Text style={styles.label}>Atende final de semana?</Text>
        <Switch 
          thumbColor="#fff" 
          trackColor={{ false: '#ccc', true: '#39CC83' }}
          value={open_on_weekends}
          onValueChange={setOpenOnWeekends}
        />
      </View>

      <RectButton style={styles.nextButton} onPress={handleCreateOrphanage}>
        <Text style={styles.nextButtonText}>Cadastrar</Text>
      </RectButton>
    </ScrollView>
  )
}
Example #19
Source File: CreateScreen.tsx    From lets-fork-native with MIT License 4 votes vote down vote up
CreateScreen = React.memo((props: Props): React.ReactElement => {
  const locale = getLocale()
  const countries = ['LR', 'MM', 'US']
  const system = countries.includes(locale.substring(3)) ? 'imperial' : 'metric'

  const units = UNITS.units[system]
  const conversion = UNITS.conversion[system]
  const symbol = currencies[locale.substring(3)] || '$'

  const { location, navigation, ws } = props
  const [categories, setCategories] = React.useState<string[]>([])
  const [price, setPrice] = React.useState([false, false, false, false])
  const [openNow, setOpenNow] = React.useState(true)
  const [radius, setRadius] = React.useState(UNITS.initialRadius[system])
  const [region, setRegion] = React.useState({
    latitude: location?.coords?.latitude || 52.520008,
    longitude: location?.coords?.longitude || 13.404954,
    latitudeDelta: 0.01,
    longitudeDelta: 0.1,
  })

  // creates a new party
  const handleCreate = (): void => {
    const pr: number[] = []
    price.forEach((p, i) => {
      if (p) pr.push(i + 1)
    })

    ws.send(JSON.stringify({
      type: 'create',
      payload: {
        categories: categories.length ? categories.join(',') : 'restaurants',
        latitude: `${region.latitude}`,
        longitude: `${region.longitude}`,
        radius: `${radius}`,
        open_now: openNow,
        price: pr.length ? pr : null,
      },
    }))
    navigation.navigate('Party')
  }

  return (
    <ScrollView>
      <MapView
        style={styles.map}
        region={region}
        onRegionChangeComplete={setRegion}
        rotateEnabled={false}
        scrollEnabled
        zoomEnabled
      >
        <Circle
          center={region}
          radius={radius}
        />
      </MapView>
      <Text style={styles.radius}>
        {`Find restaurants within: ${(radius / conversion).toFixed(1)}${units}`}
      </Text>
      <Slider
        style={styles.slider}
        minimumValue={UNITS.minimumValue[system]}
        maximumValue={UNITS.maximumValue[system]}
        minimumTrackTintColor={colors.green}
        maximumTrackTintColor={colors.green}
        value={radius}
        onValueChange={setRadius}
        step={UNITS.step[system]}
      />
      <View style={styles.openNow}>
        <Switch
          style={styles.switch}
          value={openNow}
          onValueChange={setOpenNow}
        />
        <Text style={styles.openNowText}>{openNow ? 'Currently open' : 'All restaurants'}</Text>
      </View>
      <View style={styles.price}>
        <Price selected={price} setSelected={setPrice} n={1}>{symbol}</Price>
        <Price selected={price} setSelected={setPrice} n={2}>{symbol}</Price>
        <Price selected={price} setSelected={setPrice} n={3}>{symbol}</Price>
        <Price selected={price} setSelected={setPrice} n={4}>{symbol}</Price>
      </View>
      <MultiSelect
        handleSelect={setCategories}
        items={CATEGORIES}
      />
      <View style={styles.button}>
        <Button color="purple" size="sm" onPress={(): void => handleCreate()}>
          CREATE
        </Button>
      </View>
    </ScrollView>
  )
})
Example #20
Source File: App.tsx    From react-native-slack-bottom-sheet with MIT License 4 votes vote down vote up
export default function ConfigScreen() {
  const [topOffset, setTopOffset] = React.useState(42);
  const [isShortFormEnabled, setIsShortFormEnabled] = React.useState(true);
  const [longFormHeight, setLongFormHeight] = React.useState(null);
  const [cornerRadius, setCornerRadius] = React.useState(8);
  const [springDamping, setSpringDamping] = React.useState(0.8);
  const [presentGlobally, setPresentGlobally] = React.useState(false);
  const [initialAnimation, setInitialAnimation] = React.useState(true);
  const [transitionDuration, setTransitionDuration] = React.useState(0.5);
  const [anchorModalToLongForm, setAnchorModalToLongForm] = React.useState(
    true
  );
  const [allowsDragToDismiss, setAllowsDragToDismiss] = React.useState(true);
  const [backgroundColor, setBackgroundColor] = React.useState('#000000');
  const [backgroundOpacity, setBackgroundOpacity] = React.useState(0.7);
  const [blocksBackgroundTouches, setBlocksBackgroundTouches] = React.useState(
    true
  );
  const [allowsTapToDismiss, setAllowsTapToDismiss] = React.useState(true);
  const [
    isUserInteractionEnabled,
    setIsUserInteractionEnabled,
  ] = React.useState(true);
  const [isHapticFeedbackEnabled, setIsHapticFeedbackEnabled] = React.useState(
    true
  );
  const [shouldRoundTopCorners, setShouldRoundTopCorners] = React.useState(
    true
  );
  const [showDragIndicator, setShowDragIndicator] = React.useState(true);
  const [headerHeight, setHeaderHeight] = React.useState(50);
  const [shortFormHeight, setShortFormHeight] = React.useState(500);
  const [startFromShortForm, setStartFromShortForm] = React.useState(false);
  const [componentMounted, setComponentMounted] = React.useState(true);
  const [
    interactsWithOuterScrollView,
    setInteractsWithOuterScrollView,
  ] = React.useState(false);
  const [visible, setVisible] = React.useState(true);

  return (
    <View style={{ height: '100%' }}>
      <ScrollView horizontal={true} style={{ height: '90%' }}>
        {componentMounted ? (
          <Modal
            visible={visible}
            topOffset={topOffset}
            backgroundColor={backgroundColor}
            backgroundOpacity={backgroundOpacity}
            isShortFormEnabled={isShortFormEnabled}
            longFormHeight={longFormHeight}
            cornerRadius={cornerRadius}
            springDamping={springDamping}
            transitionDuration={transitionDuration}
            anchorModalToLongForm={anchorModalToLongForm}
            allowsDragToDismiss={allowsDragToDismiss}
            allowsTapToDismiss={allowsTapToDismiss}
            isUserInteractionEnabled={isUserInteractionEnabled}
            isHapticFeedbackEnabled={isHapticFeedbackEnabled}
            shouldRoundTopCorners={shouldRoundTopCorners}
            blocksBackgroundTouches={blocksBackgroundTouches}
            showDragIndicator={showDragIndicator}
            headerHeight={headerHeight}
            shortFormHeight={400}
            startFromShortForm={startFromShortForm}
            onWillDismiss={() => {}}
            onDidDismiss={() => setVisible(false)}
            onWillTransition={({ type }: { type: String }) =>
              console.warn('onWillTransition', type)
            }
            interactsWithOuterScrollView={interactsWithOuterScrollView}
            presentGlobally={presentGlobally}
            initialAnimation={initialAnimation}
          >
            <App
              setVisible={setVisible}
              setComponentMounted={setComponentMounted}
            />
          </Modal>
        ) : null}
        <ScrollView contentContainerStyle={{ paddingTop: 30 }}>
          <Button
            title="SHOW MODAL"
            onPress={() => {
              setVisible(true);
            }}
          />

          <View style={{ flexDirection: 'row' }}>
            <View style={{ flexDirection: 'column', padding: 10 }}>
              <Text>topOffset</Text>
              <TextInput
                style={{ backgroundColor: 'grey' }}
                value={topOffset.toString()}
                keyboardType="numeric"
                onChange={({ nativeEvent: { text } }) =>
                  setTopOffset(Number(text))
                }
              />
              <Text>cornerRadius</Text>
              <TextInput
                style={{ backgroundColor: 'grey' }}
                value={cornerRadius.toString()}
                keyboardType="numeric"
                onChange={({ nativeEvent: { text } }) =>
                  setCornerRadius(Number(text))
                }
              />
              <Text>backgroundColor</Text>
              <TextInput
                style={{ backgroundColor: 'grey' }}
                value={backgroundColor}
                keyboardType="numeric"
                onChange={({ nativeEvent: { text } }) =>
                  setBackgroundColor(String(text))
                }
              />
              <Text>backgroundOpacity</Text>
              <TextInput
                style={{ backgroundColor: 'grey' }}
                value={backgroundOpacity.toString()}
                keyboardType="numeric"
                onChange={({ nativeEvent: { text } }) =>
                  setBackgroundOpacity(Number(text))
                }
              />
              <Text>springDamping</Text>
              <TextInput
                style={{ backgroundColor: 'grey' }}
                value={springDamping.toString()}
                keyboardType="numeric"
                onChange={({ nativeEvent: { text } }) =>
                  setSpringDamping(Number(text))
                }
              />
              <Text>transitionDuration</Text>
              <TextInput
                style={{ backgroundColor: 'grey' }}
                value={transitionDuration.toString()}
                keyboardType="numeric"
                onChange={({ nativeEvent: { text } }) =>
                  setTransitionDuration(Number(text))
                }
              />
              <Text>headerHeight</Text>
              <TextInput
                style={{ backgroundColor: 'grey' }}
                value={headerHeight.toString()}
                keyboardType="numeric"
                onChange={({ nativeEvent: { text } }) =>
                  setHeaderHeight(Number(text))
                }
              />
              <Text>shortFormHeight</Text>
              <TextInput
                style={{ backgroundColor: 'grey' }}
                value={shortFormHeight.toString()}
                keyboardType="numeric"
                onChange={({ nativeEvent: { text } }) =>
                  setShortFormHeight(Number(text))
                }
              />
              <Text>longFormHeight</Text>
              <TextInput
                style={{ backgroundColor: 'grey' }}
                value={longFormHeight === null ? '' : longFormHeight.toString()}
                keyboardType="numeric"
                onChange={({ nativeEvent: { text } }) =>
                  setLongFormHeight(text === '' ? null : Number(text))
                }
              />
            </View>
            <View style={{ flexDirection: 'column' }}>
              <Text>componentMounted</Text>
              <Switch
                value={componentMounted}
                onValueChange={setComponentMounted}
              />
              <Text>anchorModalToLongForm</Text>
              <Switch
                value={anchorModalToLongForm}
                onValueChange={setAnchorModalToLongForm}
              />
              <Text>isShortFormEnabled</Text>
              <Switch
                value={isShortFormEnabled}
                onValueChange={setIsShortFormEnabled}
              />
              <Text>isHapticFeedbackEnabled</Text>
              <Switch
                value={isHapticFeedbackEnabled}
                onValueChange={setIsHapticFeedbackEnabled}
              />
              <Text>allowsDragToDismiss</Text>
              <Switch
                value={allowsDragToDismiss}
                onValueChange={setAllowsDragToDismiss}
              />
              <Text>initialAnimation</Text>
              <Switch
                value={initialAnimation}
                onValueChange={setInitialAnimation}
              />
              <Text>blocksBackgroundTouches</Text>
              <Switch
                value={blocksBackgroundTouches}
                onValueChange={setBlocksBackgroundTouches}
              />
              <Text>interactsWithOuterScrollview</Text>
              <Switch
                value={interactsWithOuterScrollView}
                onValueChange={setInteractsWithOuterScrollView}
              />
              <Text>allowsTapToDismiss</Text>
              <Switch
                value={allowsTapToDismiss}
                onValueChange={setAllowsTapToDismiss}
              />
              <Text>startFromShortForm</Text>
              <Switch
                value={startFromShortForm}
                onValueChange={setStartFromShortForm}
              />
              <Text>showDragIndicator</Text>
              <Switch
                value={showDragIndicator}
                onValueChange={setShowDragIndicator}
              />
              <Text>presentGlobally</Text>
              <Switch
                value={presentGlobally}
                onValueChange={setPresentGlobally}
              />
              <Text>isUserInteractionEnabled</Text>
              <Switch
                value={isUserInteractionEnabled}
                onValueChange={setIsUserInteractionEnabled}
              />
              <Text>shouldRoundTopCorners</Text>
              <Switch
                value={shouldRoundTopCorners}
                onValueChange={setShouldRoundTopCorners}
              />
            </View>
          </View>
        </ScrollView>
      </ScrollView>
      <View style={{ height: '10%', backgroundColor: 'red' }} />
    </View>
  );
}
Example #21
Source File: ContextMenuViewTest07.tsx    From react-native-ios-context-menu with MIT License 4 votes vote down vote up
export function ContextMenuViewTest07(props: ContextMenuExampleProps) {
  const [counter, setCounter] = React.useState(0);
  const [targetViewNode, setTargetViewNode] = React.useState(null);

  const [isResizeAnimated, setIsResizeAnimated] = React.useState(false);
  const [togglePreviewType, setTogglePreviewType] = React.useState(false);
  const [togglePreviewSize, setTogglePreviewSize] = React.useState(false);
  const [toggleBgTransparent, setToggleBgTransparent] = React.useState(false);
  const [toggleTargetViewNode, setToggleTargetViewNode] = React.useState(false);
  const [togglePreferredCommitStyle, setTogglePreferredCommitStyle] = React.useState(false);

  const intervalRef = React.useRef<NodeJS.Timer | undefined>();

  React.useEffect(() => {
    return () => {
      if(!intervalRef.current) return;
      clearInterval(intervalRef.current);
    };
  }, []);

  const previewConfig: MenuPreviewConfig = {
    previewType: 
      (togglePreviewType? 'CUSTOM' : 'DEFAULT'),

    previewSize: 
      (togglePreviewSize? 'STRETCH' : 'INHERIT'),

    preferredCommitStyle: 
      (togglePreferredCommitStyle? 'pop' : 'dismiss'),

    backgroundColor: 
      (toggleBgTransparent ? 'white' :  'rgba(255,255,255,0.5)'),

    isResizeAnimated,
    ...(toggleTargetViewNode && { 
      targetViewNode 
    }),
  };

  return (
    <ContextMenuView
      style={props.style}
      menuConfig={{
        menuTitle: 'ContextMenuViewTest07',
        menuItems: [{
          actionKey  : 'add',
          actionTitle: `Add 100`,
          discoverabilityTitle: `Current counter: ${counter}`,
          icon: {
            type: 'IMAGE_SYSTEM',
            imageValue: {
              systemName: 'plus',
            },
          }
        }, 
        (counter > 0) && {
          actionKey     : 'reset',
          actionTitle   : `Reset Counter`,
          menuAttributes: ['destructive'],
          icon: {
            type: 'IMAGE_SYSTEM',
            imageValue: {
              systemName: 'trash',
            },
          }
        }],
      }}
      previewConfig={previewConfig}
      renderPreview={() => (
        <View style={[styles.previewContainer]}>
          <Text style={styles.previewTitleText}>
            {'Hello World'}
          </Text>
          {(counter % 2 === 0) && (
            <Text style={styles.previewCounterText}>
              {`Counter: ${counter}`}
            </Text>
          )}
        </View>
      )}
      onMenuWillShow={() => {
        intervalRef.current = setInterval(() => {
          setCounter((prevValue) => (prevValue + 1));
        }, 1000);
      }}
      onMenuWillHide={() => {
        if(!intervalRef.current) return;
        clearInterval(intervalRef.current);
      }}
      onPressMenuItem={({nativeEvent}) => {
        switch (nativeEvent.actionKey) {
          case 'add':
            setCounter((prevValue) => (prevValue + 100));
            break;

          case 'reset':
            setCounter(0);
            break;
        };
      }}
      >
      <ContextMenuCard
        index={props.index}
        title={'ContextMenuViewTest07'}
        subtitle={'Custom Preview'}
        description={[
          `Test for the different possible custom menu preview config`
        ]}
      >
        {toggleTargetViewNode && (
          <View
            style={styles.targetViewContainer}
            ref={ref => {
              setTargetViewNode(
                findNodeHandle(ref)
              );
            }}
          >
            <Text style={styles.targetViewText}>
              {'Target View'}
            </Text>
          </View>
        )}
        <View style={styles.rowContainer}>
          <View style={styles.textRowContainer}>
            <Text style={styles.textRowTitle}>
              {'previewType'}
            </Text>
            <Text style={styles.textRowSubtitle}>
              <Text style={styles.textRowSubtitleLabel}>
                {'Value: '}
              </Text>
              {previewConfig.previewType}
            </Text>
          </View>
          <Switch
            value={togglePreviewType}
            onValueChange={(flag) => {
              setTogglePreviewType(flag);
            }}
          />
        </View>
        <View style={styles.rowContainer}>
          <View style={styles.textRowContainer}>
            <Text style={styles.textRowTitle}>
              {'previewSize'}
            </Text>
            <Text style={styles.textRowSubtitle}>
              <Text style={styles.textRowSubtitleLabel}>
                {'Value: '}
              </Text>
              {previewConfig.previewSize}
            </Text>
          </View>
          <Switch
            value={togglePreviewSize}
            onValueChange={(flag) => {
              setTogglePreviewSize(flag);
            }}
          />
        </View>
        <View style={styles.rowContainer}>
          <View style={styles.textRowContainer}>
            <Text style={styles.textRowTitle}>
              {'backgroundColor'}
            </Text>
            <Text style={styles.textRowSubtitle}>
              <Text style={styles.textRowSubtitleLabel}>
                {'Value: '}
              </Text>
              {previewConfig.backgroundColor}
            </Text>
          </View>
          <Switch
            value={toggleBgTransparent}
            onValueChange={(flag) => {
              setToggleBgTransparent(flag);
            }}
          />
        </View>
        <View style={styles.rowContainer}>
          <View style={styles.textRowContainer}>
            <Text style={styles.textRowTitle}>
              {'isResizeAnimated'}
            </Text>
            <Text style={styles.textRowSubtitle}>
              <Text style={styles.textRowSubtitleLabel}>
                {'Value: '}
              </Text>
              {previewConfig.isResizeAnimated? 'true' : 'false'}
            </Text>
          </View>
          <Switch
            value={isResizeAnimated}
            onValueChange={(flag) => {
              setIsResizeAnimated(flag);
            }}
          />
        </View>
        <View style={styles.rowContainer}>
          <View style={styles.textRowContainer}>
            <Text style={styles.textRowTitle}>
              {'preferredCommitStyle'}
            </Text>
            <Text style={styles.textRowSubtitle}>
              <Text style={styles.textRowSubtitleLabel}>
                {'Value: '}
              </Text>
              {previewConfig.preferredCommitStyle}
            </Text>
          </View>
          <Switch
            value={togglePreferredCommitStyle}
            onValueChange={(flag) => {
              setTogglePreferredCommitStyle(flag)
            }}
          />
        </View>
        <View style={styles.rowContainer}>
          <View style={styles.textRowContainer}>
            <Text style={styles.textRowTitle}>
              {'targetViewNode'}
            </Text>
            <Text style={styles.textRowSubtitle}>
              <Text style={styles.textRowSubtitleLabel}>
                {'Value: '}
              </Text>
              {previewConfig.targetViewNode}
            </Text>
          </View>
          <Switch
            value={toggleTargetViewNode}
            onValueChange={(flag) => {
              setToggleTargetViewNode(flag);
            }}
          />
        </View>
      </ContextMenuCard>
    </ContextMenuView>
  );
}
Example #22
Source File: index.tsx    From picpay-react-native with MIT License 4 votes vote down vote up
Wallet: React.FC = () => {
  const [isVisible, setIsVisible] = useState(true);
  const [useBalance, setUseBalance] = useState(true);

  /**
   * toggle balance visibility
   */
  function handleVisibility(): void {
    setIsVisible(prevState => !prevState);
  }

  /**
   * toggle use balance
   */
  function handleUseBalance(): void {
    setUseBalance(prevState => !prevState);
  }

  return (
    <Wrapper>
      <Header
        colors={useBalance ? ['#52e78c', '#1ab563'] : ['#d3d3d3', '#868686']}
      >
        <HeaderContainer>
          <Title>Saldo PicPay</Title>
          <BalanceContainer>
            <Value>
              R$ <Bold>{isVisible ? '160.138,20' : '----'}</Bold>
            </Value>
            <EyeButton onPress={handleVisibility}>
              <Feather
                name={isVisible ? 'eye' : 'eye-off'}
                size={28}
                color="#fff"
              />
            </EyeButton>
          </BalanceContainer>
          <Info>Seu saldo está rendendo 100% do CDI</Info>

          <Actions>
            <ActionButton>
              <MaterialCommunityIcons name="cash-plus" size={25} color="#fff" />
              <ActionLabel>Adicionar</ActionLabel>
            </ActionButton>
            <ActionButton>
              <MaterialCommunityIcons
                name="bank-outline"
                size={25}
                color="#fff"
              />
              <ActionLabel>Retirar</ActionLabel>
            </ActionButton>
          </Actions>
        </HeaderContainer>
      </Header>

      <UseBalance>
        <UseBalanceTitle>Usar saldo ao pagar</UseBalanceTitle>
        <Switch value={useBalance} onValueChange={handleUseBalance} />
      </UseBalance>

      <PaymentMethods>
        <PaymentMethodsTitle>Formas de pagamento</PaymentMethodsTitle>

        <Card>
          <CardBody>
            <CardDetails>
              <CardTitle>Cadastre seu cartão de crédito</CardTitle>
              <CardInfo>
                Cadastre seu cartão de crédito para fazer pagamento mesmo quando
                não tiver saldo no seu PicPay.
              </CardInfo>
            </CardDetails>
            <Img source={creditcard} resizeMode="contain" />
          </CardBody>
          <CardAction>
            <Circle>
              <Feather name="plus" size={28} color="#0db060" />
            </Circle>
            <CardActionLabel>Adicionar cartão de crédito</CardActionLabel>
          </CardAction>
        </Card>

        <UseTicketButton>
          <MaterialCommunityIcons
            name="ticket-outline"
            size={20}
            color="#0db060"
          />
          <UseTicketLabel>Usar código promocional</UseTicketLabel>
        </UseTicketButton>
      </PaymentMethods>
    </Wrapper>
  );
}
Example #23
Source File: index.tsx    From NextLevelWeek with MIT License 4 votes vote down vote up
OrphanageData: React.FC = () => {
    const route = useRoute();
    // console.log(route.params);
    const params = route.params as IRouteParams;

    const navigation = useNavigation();

    // Campos do formulário
    const [name, setName] = useState('');
    const [about, setAbout] = useState('');
    const [instructions, setInstructions] = useState('');
    const [opening_hours, setOpeningHours] = useState('');
    const [open_on_weekends, setOpenOnWeekends] = useState(false);
    const [images, setImages] = useState<string[]>([]);

    async function handleCreateOrphanage() {
        const { latitude, longitude } = params.position;

        // console.log({
        //     name,
        //     latitude,
        //     longitude,
        //     about,
        //     instructions,
        //     opening_hours,
        //     open_on_weekends,
        // });

        const data = new FormData();

        data.append('name', name);
        data.append('about', about);
        data.append('latitude', String(latitude));
        data.append('longitude', String(longitude));
        data.append('instructions', instructions);
        data.append('opening_hours', opening_hours);
        data.append('open_on_weekends', String(open_on_weekends));

        images.forEach((image, index) => {
            data.append('images', {
                name: `image_${index}.jpg`,
                type: 'image/jpg',
                uri: image,
            } as any);
        });

        await api.post('/orphanages', data);

        navigation.navigate('OrphanagesMap');
    }

    // Função para pegar as imagens
    async function handleSelectImages() {
        // Pegando a permissão do usuário para acessar a galeria de fotos dele
        const { status } = await ImagePicker.requestCameraRollPermissionsAsync();

        // Verificando se o usuário permitiu ou não
        if (status !== 'granted') {
            alert('Eita libera aí para acessar as suas fotos!');
            return;
        }

        const result = await ImagePicker.launchImageLibraryAsync({
            allowsEditing: true,
            quality: 1,
            // Pegando apenas imagens e não vídeos
            mediaTypes: ImagePicker.MediaTypeOptions.Images,
        });
        // console.log(result);

        // Caso o usuário cancele o upload da imagem
        if (result.cancelled) {
            return;
        }

        const { uri } = result;
        // Respeitar o array de imagens
        setImages([...images, uri]);
    }

    return (
        <Container contentContainerStyle={{ padding: 24 }}>
            <Title>Dados</Title>

            <Label>Nome</Label>
            <Input
                value={name}
                onChangeText={setName}
            />

            <Label>Sobre</Label>
            <Input
                style={[{ height: 110 }]}
                multiline
                value={about}
                onChangeText={setAbout}
            />

            {/* <Label>Whatsapp</Label>
            <Input /> */}

            <Label>Fotos</Label>
            <UploadedImagesContainer>
                {images.map(image => {
                    return (
                        <UploadedImage
                            key={image}
                            source={{ uri: image }}
                        />
                    );
                })}
            </UploadedImagesContainer>
            <InputImageButton onPress={handleSelectImages}>
                <Feather name="plus" size={24} color="#15B6D6" />
            </InputImageButton>

            <Title>Visitação</Title>

            <Label>Instruções</Label>
            <Input
                style={[{ height: 110 }]}
                multiline
                value={instructions}
                onChangeText={setInstructions}
            />

            <Label>Horario de visitas</Label>
            <Input
                value={opening_hours}
                onChangeText={setOpeningHours}
            />

            <SwitchContainer>
                <Label>Atende final de semana?</Label>
                <Switch
                    thumbColor="#fff"
                    trackColor={{ false: '#ccc', true: '#39CC83' }}
                    value={open_on_weekends}
                    onValueChange={setOpenOnWeekends}
                />
            </SwitchContainer>

            <NextButton onPress={handleCreateOrphanage}>
                <NextButtonText>Cadastrar</NextButtonText>
            </NextButton>
        </Container>
    );
}
Example #24
Source File: Settings.tsx    From SQUID with MIT License 4 votes vote down vote up
Settings = () => {
  const navigation = useNavigation()
  const { enable, disable, statusText, isServiceEnabled } = useContactTracer()
  const isRegistered = Boolean(userPrivateData.getData('authToken'))
  const _onPrivacyPolicyClicked = () => {
    navigation.navigate('PrivacyPolicy')
  }

  return (
      <SafeAreaView style={{ flex: 1, backgroundColor: '#F9F9F9' }}>
        <StatusBar
          barStyle="dark-content"
          backgroundColor={COLORS.PRIMARY_LIGHT}
        />
        <ScrollView
          contentInsetAdjustmentBehavior="automatic"
          style={styles.scrollView}
        >
          <View>
            <View style={styles.sectionHeader}>
              <Text style={styles.sectionHeaderText}>{I18n.t('tracking')}</Text>
            </View>
            <View style={styles.settingsSection}>
              <View style={[styles.section]}>
                <View style={styles.horizontalRow}>
                  <View style={styles.leftArea}>
                    <Text style={styles.sectionText}>
                      {I18n.t('track_with_bluetooth')}{' '}
                    </Text>
                  </View>
                  <View style={styles.rightArea}>
                    <Switch
                      trackColor={{
                        false: '#767577',
                        true: COLORS.PRIMARY_DARK,
                      }}
                      ios_backgroundColor="#3e3e3e"
                      onValueChange={() =>
                        isServiceEnabled ? disable() : enable()
                      }
                      value={isServiceEnabled}
                    />
                  </View>
                </View>
                <Text style={styles.sectionDescription}>
                  {I18n.t('auto_turn_on_bluetooth_tracing')}
                  {I18n.t('may_cause_phone_to_consume_higher_energy')}
                  {I18n.t('you_can_choose_to_turn_off')}
                  {I18n.t('but_sys_will_not_auto_trace')}
                </Text>
              </View>
            </View>
            <View style={styles.sectionHeader}>
              <Text style={styles.sectionHeaderText}>{I18n.t('general')}</Text>
            </View>
            <View style={styles.settingsSection}>
              <TouchableHighlight onPress={_onPrivacyPolicyClicked}>
                <View style={styles.section}>
                  <Text style={styles.sectionText}>
                    {I18n.t('privacy_policy')}
                  </Text>
                </View>
              </TouchableHighlight>
              {/* <TouchableHighlight
                onPress={() => navigation.navigate('Questionaire')}
              >
                <View style={styles.section}>
                  <Text style={styles.sectionText}>
                    {I18n.t('do_questionaire_again')}
                  </Text>
                </View>
              </TouchableHighlight> */}
              <TouchableHighlight
                onPress={() => navigation.navigate('ChangeLanguage')}
              >
                <View style={styles.section}>
                  <Text style={styles.sectionText}>
                    {I18n.t('change_lang')}
                  </Text>
                </View>
              </TouchableHighlight>
              {!isRegistered && (
                <TouchableHighlight
                  onPress={() =>
                    navigation.navigate('OnboardPhone', {
                      onBack: () => {
                        navigation.pop()
                      },
                      backIcon: 'close',
                    })
                  }
                >
                  <View style={styles.section}>
                    <Text style={styles.sectionText}>
                      {I18n.t('identity_confirm')}
                    </Text>
                  </View>
                </TouchableHighlight>
              )}
            </View>
          </View>
        </ScrollView>
      </SafeAreaView>
  )
}
Example #25
Source File: OrphanageData.tsx    From happy with MIT License 4 votes vote down vote up
export default function OrphanageData() {
  const [name, setName] = useState('');
  const [about, setAbout] = useState('');
  const [instructions, setInstructions] = useState('');
  const [opening_hours, setOpeningHours] = useState('');
  const [open_on_weekends, setOpenOnWeekends] = useState(true);
  const [images, setImages] = useState<string[]>([]);

  const navigation = useNavigation();
  const routes = useRoute();
  const params = routes.params as OrphanageDataRouteParams;

  async function handleCreateOrphanage() {
    const { latitude, longitude } = params.position;

    console.log({
      name,
      latitude,
      longitude,
      about,
      instructions,
      opening_hours,
      open_on_weekends,
    });

    const data = new FormData();

    data.append('name', name);
    data.append('about', about);
    data.append('latitude', String(latitude));
    data.append('longitude', String(longitude));
    data.append('instructions', instructions);
    data.append('opening_hours', opening_hours);
    data.append('open_on_weekends', String(open_on_weekends));

    images.forEach((image, index) => {
      data.append('images', {
        name: `image_${index}.jpg`,
        type: 'image/jpg',
        uri: image,
      } as any);
    });

    await api.post('orphanages', data);

    navigation.navigate('OrphanagesMap');
  }

  async function handleSelectImages() {
    const { status } = await ImagePicker.requestCameraRollPermissionsAsync();

    if (status !== 'granted') {
      alert('Eita, precisamos de acesso às suas fotos!');
      return;
    }

    const result = await ImagePicker.launchImageLibraryAsync({
      allowsEditing: true,
      quality: 1,
      mediaTypes: ImagePicker.MediaTypeOptions.Images,
    });

    if (result.cancelled) {
      return;
    }

    const { uri: image } = result;
    setImages([...images, image]);
  }

  return (
    <ScrollView style={styles.container} contentContainerStyle={{ padding: 24 }}>
      <Text style={styles.title}>Dados</Text>

      <Text style={styles.label}>Nome</Text>
      <TextInput
        style={styles.input}
        value={name}
        onChangeText={setName}
      />

      <Text style={styles.label}>Sobre</Text>
      <TextInput
        style={[styles.input, { height: 110 }]}
        multiline
        value={about}
        onChangeText={setAbout}
      />

      {/* <Text style={styles.label}>Whatsapp</Text>
      <TextInput
        style={styles.input}
      /> */}

      <Text style={styles.label}>Fotos</Text>

      <View style={styles.uploadedImagesContaier}>
        {images.map(image => (
          <Image
            key={image}
            source={{ uri: image }}
            style={styles.uploadedImage}
          />
        ))}
      </View>

      <TouchableOpacity style={styles.imagesInput} onPress={handleSelectImages}>
        <Feather name="plus" size={24} color="#15B6D6" />
      </TouchableOpacity>

      <Text style={styles.title}>Visitação</Text>

      <Text style={styles.label}>Instruções</Text>
      <TextInput
        style={[styles.input, { height: 110 }]}
        multiline
        value={instructions}
        onChangeText={setInstructions}
      />

      <Text style={styles.label}>Horario de visitas</Text>
      <TextInput
        style={styles.input}
        value={opening_hours}
        onChangeText={setOpeningHours}
      />

      <View style={styles.switchContainer}>
        <Text style={styles.label}>Atende final de semana?</Text>
        <Switch
          thumbColor="#fff"
          trackColor={{ false: '#ccc', true: '#39CC83' }}
          value={open_on_weekends}
          onValueChange={setOpenOnWeekends}
        />
      </View>

      <RectButton style={styles.nextButton} onPress={handleCreateOrphanage}>
        <Text style={styles.nextButtonText}>Cadastrar</Text>
      </RectButton>
    </ScrollView>
  )
}