react-native#Button TypeScript Examples

The following examples show how to use react-native#Button. 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: SettingsTab.tsx    From react-native-sdk with MIT License 6 votes vote down vote up
private renderLoggedOut() {
    console.log("renderLoggedOut")
    return (
      <View style={styles.emailContainer}>
        <TextInput
          value={this.state.email}
          style={styles.emailTextInput}
          autoCapitalize="none"
          autoCompleteType="email"
          onChangeText={(text) => this.setState({ isLoggedIn: false, email: text })}
          placeholder="[email protected]" />
        <Button
          title="Login"
          onPress={this.onLoginTapped}
        />
      </View>
    )
  }
Example #2
Source File: Donut.tsx    From reanimated-arc with MIT License 6 votes vote down vote up
Donut = () => {
  const [values, setValues] = useState(generateValues());
  const setNewDonut = () => setValues(generateValues());
  return (
    <View>
      <ReanimatedArc
        color="#8EA604"
        diameter={200}
        width={20}
        arcSweepAngle={values[0].arc}
        lineCap="round"
        rotation={values[0].rotation}
        initialAnimation={false}
        style={{paddingBottom: 20}}
      />
      <ReanimatedArc
        color="#FB6107"
        diameter={200}
        width={20}
        arcSweepAngle={values[1].arc}
        lineCap="round"
        rotation={values[1].rotation}
        style={styles.absolute}
        initialAnimation={false}
      />
      <ReanimatedArc
        color="#FEC601"
        diameter={200}
        width={20}
        arcSweepAngle={values[2].arc}
        lineCap="round"
        rotation={values[2].rotation}
        style={styles.absolute}
        initialAnimation={false}
      />
      <Button title="Animate Arc!" onPress={setNewDonut} />
    </View>
  );
}
Example #3
Source File: App.tsx    From web3auth-react-native-sdk with MIT License 6 votes vote down vote up
export default function App() {
  const [key, setKey] = useState("");
  const [errorMsg, setErrorMsg] = useState("");
  const login = async () => {
    try {
      const web3auth = new Web3Auth(WebBrowser, {
        clientId: "BA0mVyeHATikwuXVhXWCNjAxHthlw0w84mUhLuxlC4KZKjvmBsbdbmEWTizJ26YzrbKSWbOZbtGYdVDm0ESuYSg",
        network: OPENLOGIN_NETWORK.TESTNET,
      });
      const state = await web3auth.login({
        loginProvider: LOGIN_PROVIDER.GOOGLE,
        redirectUrl: resolvedRedirectUrl,
      });
      setKey(state.privKey || "no key");
    } catch (e) {
      console.error(e);
      setErrorMsg(String(e));
    }
  };
  return (
    <View style={styles.container}>
      <Text>Key: {key}</Text>
      <Text>Error: {errorMsg}</Text>
      <Text>Linking URL: {resolvedRedirectUrl}</Text>
      <Text>appOwnership: {Constants.appOwnership}</Text>
      <Text>executionEnvironment: {Constants.executionEnvironment}</Text>
      <Button title="Login with Web3Auth" onPress={login} />
      <StatusBar style="auto" />
    </View>
  );
}
Example #4
Source File: SettingsTab.tsx    From react-native-sdk with MIT License 6 votes vote down vote up
private renderLoggedIn(email: String) {
    console.log(`renderLoggedIn, email: ${email}`)
    return (
      <View style={styles.emailContainer}>
        <Text style={styles.emailText}>User: {email}</Text>
        <Button
          title="Logout"
          onPress={this.onLogoutTapped}
        />
      </View>
    )
  }
Example #5
Source File: MPCScreen.tsx    From safetraceapi with GNU General Public License v3.0 6 votes vote down vote up
render() {
    const { splitOutput, joinOutput } = this.state;
    return (
      <BaseLayout>
        <MPCDetailsScrollView>
          <ShareSplitInput>Input: {this.splitInput}</ShareSplitInput>
          <ShareSplitOutput>
            Output: {JSON.stringify(splitOutput)}
          </ShareSplitOutput>

          <ShareJoinInput>
            Input: {JSON.stringify(this.joinInput)}
          </ShareJoinInput>
          <ShareJoinOutput>Output: {joinOutput}</ShareJoinOutput>

          <Button
            onPress={this.handleCallNode}
            title="Test Call to Get nodes"
          ></Button>
        </MPCDetailsScrollView>
      </BaseLayout>
    );
  }
Example #6
Source File: CreditCardForm.test.tsx    From rn-credit-card with MIT License 6 votes vote down vote up
Wrapper = () => {
  const formMethods = useForm({
    mode: 'onBlur',
    defaultValues: {
      holderName: '',
      cardNumber: '',
      expiration: '',
      cvv: '',
    },
  })
  const { handleSubmit } = formMethods

  const onSubmit = (model: FormModel) => {
    get.onSubmit(model)
  }

  return (
    <FormProvider {...formMethods}>
      <CreditCardForm />
      <Button onPress={handleSubmit(onSubmit)} title={'Submit'} />
    </FormProvider>
  )
}
Example #7
Source File: AppProvider.test.tsx    From DoobooIAP with MIT License 6 votes vote down vote up
FakeChild = (): React.ReactElement => {
  const { state, resetUser, callDefault } = useAppContext();

  return (
    <View>
      <Text testID="TEXT">{JSON.stringify(state, null, 2)}</Text>
      <Button
        testID="BUTTON"
        onPress={(): void => {
          resetUser();
        }}
        title="Button"
      />
      <Button
        testID="BUTTON_NOT_VALID"
        onPress={(): void => {
          callDefault();
        }}
        title="Button"
      />
    </View>
  );
}
Example #8
Source File: createElement.test.tsx    From react-performance-testing with MIT License 6 votes vote down vote up
test('should get correct value when Component is updated', async () => {
  const Child = () => <p>test</p>;
  const Counter = () => {
    const [count, setCount] = React.useState(0);
    return (
      <View>
        <Text>{count}</Text>
        <Child />
        <Button title="button" onPress={() => setCount((c) => c + 1)} />
      </View>
    );
  };

  const { renderCount } = perf(React);

  const { getByText } = render(<Counter />);

  fireEvent.press(getByText('button'));

  await wait(() =>
    expect(renderCount.current).toEqual({
      Counter: { value: 2 },
      Child: { value: 2 },
    }),
  );
});
Example #9
Source File: App.tsx    From react-native-credit-card-form-ui with MIT License 6 votes vote down vote up
export default function App() {
  const creditCardRef = React.useRef() as any;

  const handleSubmit = React.useCallback(() => {
    if (creditCardRef.current) {
      const { error, data } = creditCardRef.current.submit();
      console.log('ERROR: ', error);
      console.log('CARD DATA: ', data);
    }
  }, []);

  return (
    <KeyboardAvoidingView
      behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
      keyboardVerticalOffset={20}
      style={styles.container}
    >
      <CreditCard ref={creditCardRef} onValidStateChange={console.log} />
      <Button title="Submit" onPress={handleSubmit} />
    </KeyboardAvoidingView>
  );
}
Example #10
Source File: Snackbar.stories.tsx    From natds-rn with ISC License 6 votes vote down vote up
Interactive = () => {
  const [open, setOpen] = useState(false)

  return (
    <View style={{ backgroundColor: 'gainsboro', flex: 1, height: 200 }}>
      <Snackbar
        message={text('message', 'A short snackbar message')}
        buttonText={text('button text', 'ok')}
        type={select('type', snackbarTypeOptions, 'standard') as SnackbarType}
        autoHideDuration={number('auto hide duration', 5000)}
        open={open}
        onClose={() => setOpen(false)}
      />
      <Button onPress={() => setOpen(!open)} title="open snackbar" />
    </View>
  )
}
Example #11
Source File: App.tsx    From Rapid-Application-Development-with-AWS-Amplify with MIT License 6 votes vote down vote up
App = () => {

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

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

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

    );
}
Example #12
Source File: Home.tsx    From react-native-template with MIT License 6 votes vote down vote up
ReduxExample = () => {
  /**
   * Redux hooks example
   */
  const dispatch = useDispatch()
  const globalValue = useSelector(
    (state: RootStoreType) => state.example.globalValue
  )

  const ping = () => {
    if (globalValue === "PING") {
      dispatch(exampleActions.pong())
    } else {
      dispatch(exampleActions.ping())
    }
  }

  return (
    <>
      <Text style={styles.header}>Redux Example</Text>
      <Space.V s={8} />
      <Button onPress={ping} title={`Dispatch ${globalValue}`} />
    </>
  )
}
Example #13
Source File: App.tsx    From reanimated-bottom-sheet-navigator with MIT License 6 votes vote down vote up
HelloScreen = ({
  navigation,
}: BottomSheetScreenProps<SheetParamList>) => (
  <View style={styles.screen}>
    <Button title="Open sheet" onPress={navigation.openSheet} />
    <Button title="Close sheet" onPress={navigation.closeSheet} />
    <Button title="Snap to middle" onPress={() => navigation.snapSheet(1)} />
  </View>
)
Example #14
Source File: Login.tsx    From react-native-sdk with MIT License 6 votes vote down vote up
private renderLoggedOut() {
    console.log("renderLoggedOut")
    return (
      <View style={styles.emailContainer}>
        <TextInput testID='loginText'
          value={this.state.email}
          style={styles.emailTextInput}
          autoCapitalize="none"
          autoCompleteType="email"
          onChangeText={(text) => this.setState({ isLoggedIn: false, email: text })}
          placeholder="[email protected]" />
        <Button
          testID="loginBtn"
          title="Login"
          onPress={this.onLoginTapped}
        />
      </View>
    )
  }
Example #15
Source File: Login.tsx    From react-native-keycloak with MIT License 6 votes vote down vote up
Login = () => {
  const { keycloak } = useKeycloak();

  return (
    <View style={styles.container}>
      <Text>{`Welcome ${keycloak?.authenticated} - ${keycloak?.token}!`}</Text>
      <Button onPress={() => keycloak?.login()} title="Login" />
    </View>
  );
}
Example #16
Source File: Snackbar.stories.tsx    From natds-rn with ISC License 5 votes vote down vote up
Colors = () => {
  const [standard, setStandard] = useState(false)
  const [info, setInfo] = useState(false)
  const [warning, setWarning] = useState(false)
  const [error, setError] = useState(false)
  const [success, setSuccess] = useState(false)
  const [multi, setMulti] = useState(false)
  const [withButton, setWithButton] = useState(false)

  const defaultMessage = 'A short snackbar message'
  const multiMessage = 'A longer message to hopefully show how it behaves when there is a multiline snackbar. The text will be truncated and the missing text at the end of the line will be indicated by an ellipsis glyph'

  return (
    <StoryWrapper title="Variants">
      <StoryContainer title="Standard">
        <View style={{ backgroundColor: 'gainsboro', flex: 1, height: 200 }}>
          <Snackbar message={defaultMessage} open={standard} onClose={() => setStandard(false)} />
          <Button onPress={() => setStandard(!standard)} title="open standard snackbar" />
        </View>
      </StoryContainer>

      <StoryContainer title="Info">
        <View style={{ backgroundColor: 'gainsboro', flex: 1, height: 200 }}>
          <Snackbar message={defaultMessage} open={info} onClose={() => setInfo(false)} type="info" />
          <Button onPress={() => setInfo(!info)} title="open info snackbar" />
        </View>
      </StoryContainer>

      <StoryContainer title="Warning">
        <View style={{ backgroundColor: 'gainsboro', flex: 1, height: 200 }}>
          <Snackbar message={defaultMessage} open={warning} onClose={() => setWarning(false)} type="warning" />
          <Button onPress={() => setWarning(!warning)} title="open warning snackbar" />
        </View>
      </StoryContainer>

      <StoryContainer title="Error">
        <View style={{ backgroundColor: 'gainsboro', flex: 1, height: 200 }}>
          <Snackbar message={defaultMessage} open={error} onClose={() => setError(false)} type="error" />
          <Button onPress={() => setError(!error)} title="open error snackbar" />
        </View>
      </StoryContainer>

      <StoryContainer title="Success">
        <View style={{ backgroundColor: 'gainsboro', flex: 1, height: 200 }}>
          <Snackbar message={defaultMessage} open={success} onClose={() => setSuccess(false)} type="success" />
          <Button onPress={() => setSuccess(!success)} title="open success snackbar" />
        </View>
      </StoryContainer>

      <StoryContainer title="Multiline">
        <View style={{ backgroundColor: 'gainsboro', flex: 1, height: 200 }}>
          <Snackbar message={multiMessage} open={multi} onClose={() => setMulti(false)} type="standard" />
          <Button onPress={() => setMulti(!multi)} title="open multiline snackbar" />
        </View>
      </StoryContainer>

      <StoryContainer title="Multiline with Button">
        <View style={{ backgroundColor: 'gainsboro', flex: 1, height: 200 }}>
          <Snackbar message={multiMessage} open={withButton} onClose={() => setWithButton(false)} type="standard" buttonText="ok" />
          <Button onPress={() => setWithButton(!withButton)} title="open multiline snackbar with button" />
        </View>
      </StoryContainer>
    </StoryWrapper>
  )
}
Example #17
Source File: index.tsx    From jellyfin-audio-player with MIT License 5 votes vote down vote up
export default function SetJellyfinServer() {
    const defaultStyles = useDefaultStyles();
    // State for first screen
    const [serverUrl, setServerUrl] = useState<string>();
    const [isLogginIn, setIsLogginIn] = useState<boolean>(false);

    // Handlers needed for dispatching stuff
    const dispatch = useAppDispatch();
    const navigation = useNavigation();

    // Save creedentials to store and close the modal
    const saveCredentials = useCallback((credentials) => {
        dispatch(setJellyfinCredentials(credentials));
        navigation.dispatch(StackActions.popToTop());    
    }, [navigation, dispatch]);

    return (
        <Modal>
            {isLogginIn ? (
                <CredentialGenerator 
                    serverUrl={serverUrl as string}
                    onCredentialsRetrieved={saveCredentials}
                />
            ) : (
                <View style={{ padding: 20, flex: 1, justifyContent: 'center', alignItems: 'center' }}>
                    <Text>
                        {t('set-jellyfin-server-instruction')}
                    </Text>
                    <Input
                        placeholder="https://jellyfin.yourserver.io/"
                        onChangeText={setServerUrl}
                        value={serverUrl} 
                        keyboardType="url"
                        autoCapitalize="none"
                        autoCorrect={false}
                        style={[ defaultStyles.input, { width: '100%' } ]}
                    />
                    <Button
                        title={t('set-jellyfin-server')}
                        onPress={() => setIsLogginIn(true)}
                        disabled={!serverUrl?.length} 
                        color={THEME_COLOR}
                    />
                </View>
            )}
        </Modal>
    );
}
Example #18
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 #19
Source File: IDMatch.tsx    From ito-app with GNU General Public License v3.0 5 votes vote down vote up
IDMatch: React.FC<{
  navigation: IDMatchScreenNavigationProp;
}> = ({navigation}) => {
  return (
    <View style={styles.container}>
      <View style={styles.logoWrapper}>
        <Text style={styles.logo}>ito</Text>
        <AlphaNotice
          rootStyle={styles.alphaNoticeRoot}
          textStyle={styles.alphaNoticeText}
        />
      </View>
      <View style={styles.lastFetchRow}>
        <Text style={styles.lastFetch}>Last ID fetch: today 11:04</Text>
        <Icon name="refresh-ccw" size={18} style={styles.refreshIcon} />
      </View>

      <View style={styles.radiusContainer}>
        <Text style={styles.radius1} />
        <Text style={styles.radius2} />
        <Text style={styles.radius3} />
      </View>
      <Text style={styles.contacts}>just a few contacts around you</Text>
      <View style={styles.bottomButtonContainer}>
        <Button
          title="I think I'm infected"
          disabledTitleStyle={styles.buttonInfectedTitle}
          disabledStyle={styles.buttonInfected}
          disabled
        />
      </View>
      <View
        style={{
          backgroundColor: 'white',
          position: 'absolute',
          top: '40%',
          marginLeft: 20,
          marginRight: 20,
          padding: 16,
        }}>
        <Text
          style={{
            fontFamily: 'Ubuntu-R',
            fontSize: 18,
            textAlign: 'center',
            marginBottom: 16,
          }}>
          We just discovered you have been in contact with a COVID-19 case.
          {'\n'}
          Don't panic!
        </Text>
        <BasicButton
          title="What to do next?"
          onPress={(): void => navigation.navigate('HomeBluetooth')}
        />
      </View>
    </View>
  );
}
Example #20
Source File: Landing.tsx    From react-native-template with MIT License 5 votes vote down vote up
Landing = ({ navigation }: Props) => {
  const goHome = () => navigation.navigate("Home")

  return (
    <View>
      <StatusBar
        barStyle={Platform.OS === "ios" ? "dark-content" : "light-content"}
      />
      <Text style={styles.env}>
        Environment:{" "}
        <Text
          style={{
            fontWeight: "600",
          }}
        >
          {BuildConfig.ENV}
        </Text>
      </Text>
      <ScrollView
        contentInsetAdjustmentBehavior="automatic"
        style={styles.scrollView}
      >
        <Header />
        <Text style={styles.templateTitle} testID="title">
          @osamaq/react-native-template
        </Text>
        {global.HermesInternal == null ? null : (
          <View style={styles.engine}>
            <Text style={styles.footer}>Engine: Hermes</Text>
          </View>
        )}
        <View style={styles.body}>
          <View style={styles.signinBtn}>
            <Button
              title="NAVIGATE HOME"
              onPress={goHome}
              testID="goHomeBtn"
              color="lightpink"
            />
          </View>
          <View style={styles.sectionContainer}>
            <Text style={styles.sectionTitle}>Step One</Text>
            <Text style={styles.sectionDescription}>
              Edit <Text style={styles.highlight}>Landing.tsx</Text> to change
              this screen and then come back to see your edits.
            </Text>
          </View>
          <View style={styles.sectionContainer}>
            <Text style={styles.sectionTitle}>See Your Changes</Text>
            <Text style={styles.sectionDescription}>
              <ReloadInstructions />
            </Text>
          </View>
          <View style={styles.sectionContainer}>
            <Text style={styles.sectionTitle}>Debug</Text>
            <Text style={styles.sectionDescription}>
              <DebugInstructions />
            </Text>
          </View>
          <View style={styles.sectionContainer}>
            <Text style={styles.sectionTitle}>Learn More</Text>
            <Text style={styles.sectionDescription}>
              Read the docs to discover what to do next:
            </Text>
          </View>
          <LearnMoreLinks />
        </View>
      </ScrollView>
    </View>
  )
}
Example #21
Source File: Stopwatch.tsx    From reanimated-arc with MIT License 5 votes vote down vote up
Stopwatch = () => {
  const [currentTime, setCurrentTime] = useState(30);
  const [currentTimeText, setCurrentTimeText] = useState('00:30');
  const [stopWatchActive, setStopWatchActive] = useState(false);

  useEffect(() => {
    if (stopWatchActive) {
      const timeout1 = setTimeout(() => {
        if (currentTime < 1) {
          setStopWatchActive(false);
        } else {
          setCurrentTime(currentTime - 1);
        }
      }, 1000);
      const timeout2 = setTimeout(() => {
        setCurrentTimeText(`00:${currentTime < 10 ? '0' : ''}${currentTime}`);
      }, 150);

      return () => {
        clearTimeout(timeout1);
        clearTimeout(timeout2);
      };
    }
  }, [currentTime, stopWatchActive]);

  const startCounting = () => {
    setCurrentTime(30);
    setStopWatchActive(true);
  };

  return (
    <View>
      <View style={[styles.container]}>
        <ReanimatedArc
          color="lightgrey"
          diameter={195}
          width={10}
          arcSweepAngle={360}
          lineCap="round"
          initialAnimation={false}
        />
        <ReanimatedArc
          color="#8EA604"
          diameter={200}
          width={16}
          arcSweepAngle={currentTime * 6}
          animationDuration={200}
          easing={easing}
          lineCap="round"
          style={styles.absolute}
          initialAnimation={false}
        />
        <Text style={[styles.absolute, styles.time]}>{currentTimeText}</Text>
      </View>
      <View style={{paddingTop: 20}}>
        <Button title="Start stopwatch" onPress={startCounting} />
      </View>
    </View>
  );
}
Example #22
Source File: App.tsx    From react-native-dynamic with MIT License 5 votes vote down vote up
function Counter() {
	const [counter, setCounter] = useState(0)
	return <Button title={counter.toString()} onPress={() => setCounter((i) => i + 1)} />
}
Example #23
Source File: Progress.tsx    From reanimated-arc with MIT License 5 votes vote down vote up
Progress = () => {
  const arcAngle = useRef(new Reanimated.Value(Math.random() * 240));
  const [text, setText] = useState('0%');
  const randomizeProgress = useCallback(() => {
    Reanimated.timing(arcAngle.current, {
      toValue: Math.random() * 240,
      easing: Easing.inOut(Easing.quad),
      duration: 1000,
    }).start();
  }, []);

  return (
    <View>
      <View style={styles.container}>
        <Reanimated.Code
          exec={Reanimated.call([arcAngle.current], ([value]) => {
            setText(`${Math.round((value / 240) * 100)}%`);
          })}
        />
        <ReanimatedArcBase
          color="lightgrey"
          diameter={200}
          width={20}
          arcSweepAngle={240}
          lineCap="round"
          rotation={240}
          style={styles.absolute}
        />
        <ReanimatedArcBase
          color="purple"
          diameter={200}
          width={20}
          arcSweepAngle={arcAngle.current}
          lineCap="round"
          rotation={240}
          style={styles.absolute}
        />
        <Text style={styles.text}>{text}</Text>
      </View>
      <Button title="Randomize progress" onPress={randomizeProgress} />
    </View>
  );
}
Example #24
Source File: expenditure.tsx    From THUInfo with MIT License 5 votes vote down vote up
ExpenditureScreen = () => {
	const [[expenditures, income, outgo, remainder], setExpenditures] = useState<
		[Record[], number, number, number]
	>([[], 0, 0, 0]);

	const [beg, setBeg] = useState(dayjs().add(-1, "month").toDate());
	const [end, setEnd] = useState(dayjs().toDate());
	const [refreshing, setRefreshing] = useState(false);

	const themeName = useColorScheme();
	const theme = themes(themeName);

	const refresh = () => {
		setRefreshing(true);
		helper
			.getExpenditures(beg, end)
			.then(setExpenditures)
			.catch((e) => {
				Snackbar.show({
					text: getStr("networkRetry") + e?.message,
					duration: Snackbar.LENGTH_SHORT,
				});
			})
			.then(() => setRefreshing(false));
	};

	// eslint-disable-next-line react-hooks/exhaustive-deps
	useEffect(refresh, []);

	return (
		<View style={{padding: 10, flex: 1}}>
			<View style={{flexDirection: "row"}}>
				<Money title={getStr("income")} money={income} />
				<Money title={getStr("outgo")} money={outgo} />
				<Money title={getStr("remainder")} money={refreshing ? 0 : remainder} />
			</View>
			{!helper.mocked() && (
				<View style={styles.header}>
					<DatePickerTrigger
						date={beg}
						onChange={setBeg}
						disabled={refreshing}
						text={Platform.OS === "ios" ? getStr("begDate") : ""}
					/>
					<DatePickerTrigger
						date={end}
						onChange={setEnd}
						disabled={refreshing}
						text={Platform.OS === "ios" ? getStr("endDate") : ""}
					/>
					<Button
						title={getStr("query")}
						onPress={refresh}
						disabled={refreshing}
					/>
				</View>
			)}
			<View style={styles.container}>
				<FlatList
					data={expenditures}
					refreshControl={
						<RefreshControl
							refreshing={refreshing}
							onRefresh={refresh}
							colors={[theme.colors.accent]}
						/>
					}
					renderItem={({item}) => <ExpenditureCard record={item} />}
					keyExtractor={(item, index) => `${item.date}-${item.value}-${index}`}
				/>
			</View>
		</View>
	);
}
Example #25
Source File: App.tsx    From sp-react-native-in-app-updates with MIT License 5 votes vote down vote up
render() {
    const { needsUpdate, error } = this.state;
    let statusTxt;
    if (needsUpdate) {
      statusTxt = 'YES';
    } else if (needsUpdate === false) {
      statusTxt = 'NO';
    } else if (error) {
      statusTxt = 'Error, check below';
    } else {
      statusTxt = 'Not sure yet';
    }
    return (
      <>
        <StatusBar barStyle="dark-content" />
        <SafeAreaView>
          <View style={styles.container}>
            <View style={styles.aButton}>
              <Button
                title="Check for updates"
                color={BUTTON_COLOR}
                onPress={this.checkForUpdates}
              />
            </View>
            <View style={styles.aButton}>
              <Button
                disabled={!needsUpdate}
                title="Start Updating"
                color={BUTTON_COLOR}
                onPress={this.startUpdating}
              />
            </View>
            <View
              // eslint-disable-next-line react-native/no-inline-styles
              style={{
                // backgroundColor: 'pink'
                alignItems: 'center',
              }}
            >
              <Text
                style={styles.textStyle}
              >{`Needs update: ${'\n'}${statusTxt}`}</Text>
            </View>
            {error ? (
              <View style={styles.errorContainer}>
                <Text style={styles.errorTextStyle}>{`Error: ${error}`}</Text>
              </View>
            ) : null}
          </View>
        </SafeAreaView>
      </>
    );
  }
Example #26
Source File: App.tsx    From react-native-use-websocket with MIT License 5 votes vote down vote up
App: React.FC = () => {
  const socketUrl = 'wss://echo.websocket.org';
  const messageHistory = React.useRef<any>([]);

  const { sendMessage, lastMessage, readyState } = useWebSocket(socketUrl);

  messageHistory.current = React.useMemo(
    () => messageHistory.current.concat(lastMessage),
    [lastMessage]
  );

  const sendM = () => sendMessage('Hello');
  const handleClickSendMessage = React.useCallback(sendM, [sendM]);

  const connectionStatus = {
    [ReadyState.CONNECTING]: 'Connecting',
    [ReadyState.OPEN]: 'Open',
    [ReadyState.CLOSING]: 'Closing',
    [ReadyState.CLOSED]: 'Closed',
    [ReadyState.UNINSTANTIATED]: 'Uninstantiated',
  };

  return (
    <>
      <Button
        onPress={handleClickSendMessage}
        disabled={readyState !== ReadyState.OPEN}
        title={"Click Me to send 'Hello'"}
      />
      <Text>The WebSocket is currently {connectionStatus}</Text>
      {lastMessage ? <Text>Last message: {lastMessage.data}</Text> : null}
      <FlatList
        keyExtractor={(item, i) => {
          return item.toString() + i.toString();
        }}
        data={messageHistory.current}
        renderItem={({ item }) =>
          item && item.message && <Text>{item.message.data}</Text>
        }
      />
    </>
  );
}
Example #27
Source File: Donut2.tsx    From reanimated-arc with MIT License 5 votes vote down vote up
Donut2 = () => {
  const [values, setValues] = useState([0, 0, 0]);
  const setDonutValues = () => setValues(targetValues);
  return (
    <View>
      <ReanimatedArc
        color="#F7AEF8"
        diameter={200}
        width={20}
        arcSweepAngle={values[0]}
        lineCap="round"
        rotation={0}
        initialAnimation={false}
        easing={easing}
        style={{paddingBottom: 20}}
      />
      <ReanimatedArc
        color="#7A85E8"
        diameter={200}
        width={20}
        arcSweepAngle={values[1]}
        lineCap="round"
        rotation={targetValues[0] + space}
        style={styles.absolute}
        initialAnimation={false}
        easing={easing}
      />
      <ReanimatedArc
        color="#50C9CE"
        diameter={200}
        width={20}
        arcSweepAngle={values[2]}
        lineCap="round"
        rotation={targetValues[0] + targetValues[1] + space * 2}
        style={styles.absolute}
        initialAnimation={false}
        easing={easing}
      />
      <Button title="Show donut" onPress={setDonutValues} />
    </View>
  );
}
Example #28
Source File: App.tsx    From Rapid-Application-Development-with-AWS-Amplify with MIT License 5 votes vote down vote up
App = () => {
  const [authState, setAuthState] = React.useState<any>();
  const [user, setUser] = React.useState<any | undefined>();

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

  return authState && user ? (
    <View style={styles.container}>
      <Text>Good day, {authState && user ? user.username : "mate"}</Text>
      <Button
        title="Sign out"
        onPress={() => {
          Auth.signOut()
            .then(() => {
              setAuthState(null);
              setUser(null);
            })
            .catch((info: any) => console.log("Info: ", info));
        }}
      />
    </View>
  ) : (
    <Authenticator
      signUpConfig={signUpConfig}
      onStateChange={(authState: any) => {
        setAuthState(authState);
        setCurrentUser();
      }}
      theme={GreatTheme}
    />
  );
}
Example #29
Source File: App.tsx    From react-native-sdk with MIT License 5 votes vote down vote up
render() {
    return (
      <SafeAreaView style={styles.container}>
        <ScrollView
          contentInsetAdjustmentBehavior="automatic"
          style={styles.scrollView}>
          <View style={styles.buttonContainer}>
            <Login />
          </View>
          <View style={styles.buttonContainer}>
            <Button testID='sendInAppBtn' title="Send In-App" onPress={() => {
              RNE2E.sendCommand("send-in-app", { campaignId: sendInAppCampaignId })
            }} />
          </View>
          <View style={styles.buttonContainer}>
            <Button testID='skipInAppBtn' title="Skip In-App" onPress={() => {
              RNE2E.sendCommand("send-in-app", { campaignId: skipInAppCampaignId })
            }} />
          </View>
          <View style={styles.buttonContainer}>
            <Button testID="customActionBtn" title="Custom Action" onPress={() => {
              RNE2E.sendCommand("send-in-app", { campaignId: customActionCampaignId })
            }} />
          </View>
          <View style={styles.buttonContainer}>
            <Button testID="openDeepLinkBtn" title="Url Delegate Open Deep Link" onPress={() => {
              RNE2E.sendCommand("send-in-app", { campaignId: openDeepLinkCampaignId })
            }} />
          </View>
          <View style={styles.buttonContainer}>
            <Button testID="openSafariBtn" title="Url Delegate Open Safari" onPress={() => {
              RNE2E.sendCommand("send-in-app", { campaignId: openSafariCampaignId })
            }} />
          </View>

          <View style={styles.buttonContainer}>
            <Button title="Get In-app Messages" onPress={() => {
              Iterable.inAppManager.getMessages().then(messages => {
                console.log("messages: " + messages.length)
                messages.forEach(message => {
                  console.log(JSON.stringify(message, null, 2))
                })
              })
            }} />
          </View>
          <View style={styles.buttonContainer}>
            <Button title="Remove In-App Message" onPress={() => {
              Iterable.inAppManager.getMessages().then(messages => {
                console.log("total messages: " + messages.length)
                if (messages.length > 0) {
                  Iterable.inAppManager.removeMessage(messages[messages.length - 1], IterableInAppLocation.inbox, IterableInAppDeleteSource.deleteButton)
                }
              })
            }} />
          </View>
          <View style={styles.buttonContainer}>
            <Button testID="clearAllInApps" title="Clear All In-App Messages" onPress={() => {
              console.log("clearAllInApps")
              RNE2E.clearAllInAppMessages().then(success => {
                console.log("cleared all in-app messages: " + success)
                this.setState({ statusText: "Cleared all in-apps" })
              })
            }} />
          </View>
          <View style={styles.buttonContainer}>
            <Button testID="resetBtn" title="Reset" onPress={() => {
              console.log("reset")
              this.setState({ statusText: "" })
            }} />
          </View>
        </ScrollView>
        <View style={styles.textContainer}>
          <Text testID='statusText' style={styles.statusText}>{this.state.statusText}</Text>
        </View>
      </SafeAreaView>
    )
  }