@expo/vector-icons#MaterialCommunityIcons TypeScript Examples

The following examples show how to use @expo/vector-icons#MaterialCommunityIcons. 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: index.tsx    From TwitterClone with MIT License 6 votes vote down vote up
NewTweetButton = () => {

  const navigation = useNavigation();

  const onPress = () => {
    navigation.navigate('NewTweet');
  }

  return (
    <TouchableOpacity
      activeOpacity={0.8}
      style={styles.button}
      onPress={onPress}
    >
      <MaterialCommunityIcons name={"feather"} size={30} color="white" />
    </TouchableOpacity>
  )
}
Example #2
Source File: Navbar.tsx    From make-a-fortune with MIT License 6 votes vote down vote up
Navbar: React.FC<{
  composeButton?: boolean;
}> = () => {
  const ComposeButton = () => (
    <IconButton
      variant="ghost"
      size="sm"
      colorScheme="lightBlue"
      icon={
        <Icon
          as={<MaterialCommunityIcons name="plus" />}
          size="sm"
          color="lightBlue.500"
        />
      }
    >
      {/* 发帖 */}
    </IconButton>
  );
  const AvatarButton = () => <Avatar size="sm">A</Avatar>;

  return (
    <HStack
      safeAreaTop
      px={5}
      justifyContent="space-between"
      alignItems="center"
    >
      <AvatarButton />
      <Logo />
      <ComposeButton />
    </HStack>
  );
}
Example #3
Source File: Home.native.tsx    From make-a-fortune with MIT License 6 votes vote down vote up
Layout = () => (
  <Box flex={1} bgColor="white">
    <Fab
      placement="bottom-right"
      mb={20}
      size="sm"
      colorScheme="blue"
      shadow={3}
      icon={
        <Icon
          color="white"
          as={<MaterialCommunityIcons name="plus" />}
          size="sm"
        />
      }
    />
    <ThreadList />
  </Box>
)
Example #4
Source File: index.tsx    From selftrace with MIT License 6 votes vote down vote up
Icon = {
  Question: (props: Props) => <FontAwesome name="question" size={25} {...props} />,
  MapMarker: (props: Props) => <MaterialCommunityIcons name="map-marker" size={25} {...props} />,
  Earth: (props: Props) => <MaterialCommunityIcons name="earth" size={25} {...props} />,
  Lock: (props: Props) => <Foundation name="lock" size={25} {...props} />,
  Form: (props: Props) => <AntDesign name="form" size={23} {...props} />,
  Person: (props: Props) => <MaterialIcons name="person" size={25} {...props} />,
  MapMarkerMultiple: (props: Props) => (
    <MaterialCommunityIcons name="map-marker-multiple" size={23} {...props} />
  ),
}
Example #5
Source File: Checkbox.tsx    From vsinder with Apache License 2.0 6 votes vote down vote up
Checkbox: React.FC<Props> = ({ selected, style }) => {
  const [{ buttonBackground }] = React.useContext(ThemeContext);
  return selected ? (
    <MaterialCommunityIcons
      style={[style, { height: size }]}
      color={buttonBackground}
      size={size}
      name="checkbox-marked"
    />
  ) : (
    <MaterialCommunityIcons
      style={[style, { height: size }]}
      size={size}
      color={buttonBackground}
      name="checkbox-blank-outline"
    />
  );
}
Example #6
Source File: BottomTabNavigator.tsx    From SpotifyClone with MIT License 6 votes vote down vote up
export default function BottomTabNavigator() {
  const colorScheme = useColorScheme();

  return (
    <BottomTab.Navigator
      initialRouteName="TabOne"
      tabBarOptions={{ activeTintColor: Colors[colorScheme].tint }}>
      <BottomTab.Screen
        name="Home"
        component={TabOneNavigator}
        options={{
          tabBarIcon: ({ color }) => <Entypo name="home" size={30} style={{ marginBottom: -3 }} color={color} />,
        }}
      />
      <BottomTab.Screen
        name="Search"
        component={TabTwoNavigator}
        options={{
          tabBarIcon: ({ color }) => <EvilIcons name="search" size={30} style={{ marginBottom: -3 }} color={color} />,
        }}
      />
      <BottomTab.Screen
        name="Your Library"
        component={TabTwoNavigator}
        options={{
          tabBarIcon: ({ color }) => <MaterialCommunityIcons name="library-music-outline" size={30} style={{ marginBottom: -3 }} color={color} />,
        }}
      />
      <BottomTab.Screen
        name="Premium"
        component={TabTwoNavigator}
        options={{
          tabBarIcon: ({ color }) => <FontAwesome5 name="spotify" size={30} style={{ marginBottom: -3 }} color={color} />,
        }}
      />
    </BottomTab.Navigator>
  );
}
Example #7
Source File: MainTabStack.tsx    From vsinder with Apache License 2.0 5 votes vote down vote up
MainTabStack: React.FC<MainTabStackProps> = ({}) => {
  const { show } = useShowTabs();
  const {
    editorBackground,
    buttonBackground,
    buttonHoverBackground,
  } = useTheme();
  const cache = useQueryCache();

  useEffect(() => {
    const _handleAppStateChange = (nextAppState: AppStateStatus) => {
      if (nextAppState === "active") {
        cache.invalidateQueries(`/matches/0`);
        getSocket().reconnect();
      } else if (nextAppState === "background") {
        getSocket().close();
      }
    };

    AppState.addEventListener("change", _handleAppStateChange);

    return () => {
      AppState.removeEventListener("change", _handleAppStateChange);
    };
  }, []);

  return (
    <Tab.Navigator
      screenOptions={({ route }) => ({
        tabBarIcon: ({ focused }) => {
          const size = 24;
          const color = focused ? buttonHoverBackground : buttonBackground;

          if (route.name === "swiper") {
            return <Entypo name="code" size={size} color={color} />;
          } else if (route.name === "profile") {
            return (
              <MaterialCommunityIcons
                name="account"
                size={size}
                color={color}
              />
            );
          } else if (route.name === "matches") {
            return <MessageIcon size={size} color={color} />;
          }

          return null;
        },
      })}
      swipeEnabled={false}
      tabBarOptions={{
        style: {
          height: show ? undefined : 0,
          backgroundColor: editorBackground,
        },
        indicatorStyle: {
          backgroundColor: buttonHoverBackground,
        },
        showIcon: true,
        showLabel: false,
      }}
      initialRouteName={"swiper"}
    >
      <Tab.Screen name="swiper" component={SwiperScreen} />
      <Tab.Screen name="matches" component={MatchesStack} />
      <Tab.Screen name="profile" component={ProfileStack} />
    </Tab.Navigator>
  );
}
Example #8
Source File: MainTabStack.tsx    From vsinder-app with Apache License 2.0 5 votes vote down vote up
MainTabStack: React.FC<MainTabStackProps> = ({}) => {
  const { show } = useShowTabs();
  const {
    editorBackground,
    buttonBackground,
    buttonHoverBackground,
  } = useTheme();

  useEffect(() => {
    const _handleAppStateChange = (nextAppState: AppStateStatus) => {
      if (nextAppState === "active") {
        getSocket().reconnect();
      } else if (nextAppState === "background") {
        getSocket().close();
      }
    };

    AppState.addEventListener("change", _handleAppStateChange);

    return () => {
      AppState.removeEventListener("change", _handleAppStateChange);
    };
  }, []);

  return (
    <Tab.Navigator
      screenOptions={({ route }) => ({
        tabBarIcon: ({ focused }) => {
          const size = 24;
          const color = focused ? buttonHoverBackground : buttonBackground;

          if (route.name === "swiper") {
            return <Entypo name="code" size={size} color={color} />;
          } else if (route.name === "profile") {
            return (
              <MaterialCommunityIcons
                name="account"
                size={size}
                color={color}
              />
            );
          } else if (route.name === "matches") {
            return <MessageIcon size={size} color={color} />;
          }

          return null;
        },
      })}
      swipeEnabled={false}
      tabBarOptions={{
        style: {
          height: show ? undefined : 0,
          backgroundColor: editorBackground,
        },
        indicatorStyle: {
          backgroundColor: buttonHoverBackground,
        },
        showIcon: true,
        showLabel: false,
      }}
      initialRouteName={"swiper"}
    >
      <Tab.Screen name="swiper" component={SwiperScreen} />
      <Tab.Screen name="matches" component={MatchesStack} />
      <Tab.Screen name="profile" component={ProfileStack} />
    </Tab.Navigator>
  );
}
Example #9
Source File: AppNavigator.tsx    From tic-tac-toe-app with MIT License 5 votes vote down vote up
AppNavigator: React.FC = () => {
    const theme = useSelector(selectTheme);
    const systemThemeEnabled = useSelector(selectSystemTheme);

    const dispatch = useDispatch();

    const deviceTheme = useColorScheme();

    if (
        (deviceTheme === 'light' || deviceTheme === 'dark') &&
        systemThemeEnabled
    ) {
        dispatch(setCurrentTheme(deviceTheme));
    }

    return (
        <AppearanceProvider>
            <NavigationContainer>
                <Tab.Navigator
                    screenOptions={({ route }) => ({
                        tabBarIcon: ({ focused, size }) => {
                            const color = focused ? 'white' : 'lightgrey';
                            const iconName =
                                route.name === 'Settings'
                                    ? 'settings'
                                    : 'gamepad';
                            return (
                                <MaterialCommunityIcons
                                    color={color}
                                    name={iconName}
                                    size={size}
                                />
                            );
                        },
                    })}
                    tabBarOptions={{
                        showLabel: false,
                        style: {
                            backgroundColor: colors[theme].main,
                            shadowColor: 'transparent',
                            borderTopWidth: 0,
                        },
                    }}
                >
                    <Tab.Screen name="Home" component={GameStackScreen} />
                    <Tab.Screen
                        name="Settings"
                        component={SettingsStackScreen}
                    />
                </Tab.Navigator>
            </NavigationContainer>
        </AppearanceProvider>
    );
}
Example #10
Source File: index.tsx    From tiktok-clone with MIT License 5 votes vote down vote up
Record: React.FC = () => {
  const [hasPermission, setHasPermission] = useState<boolean | null>(null);
  const [type, setType] = useState(Camera.Constants.Type.back);

  const navigation = useNavigation();
  useEffect(() => {
    async function permission(): Promise<void> {
      const { status } = await Camera.requestPermissionsAsync();
      setHasPermission(status === 'granted');
      StatusBar.setHidden(true);
    }
    permission();
  }, []);

  if (hasPermission === null) {
    return <View />;
  }
  if (hasPermission === false) {
    return <Text>No access to camera</Text>;
  }

  return (
    <Camera style={{ flex: 1 }} type={type}>
      <Container>
        <Header>
          <Button
            onPress={() => {
              StatusBar.setHidden(false);
              navigation.goBack();
            }}
          >
            <AntDesign name="close" size={28} color="#fff" />
          </Button>
          <Button>
            <Row>
              <FontAwesome name="music" size={18} color="#fff" />
              <Description>Sons</Description>
            </Row>
          </Button>
          <Button
            onPress={() => {
              setType(
                type === Camera.Constants.Type.back
                  ? Camera.Constants.Type.front
                  : Camera.Constants.Type.back,
              );
            }}
          >
            <MaterialCommunityIcons
              name="rotate-right"
              size={28}
              color="#fff"
            />
          </Button>
        </Header>
        <RecordButton />
      </Container>
    </Camera>
  );
}
Example #11
Source File: HorizontalFlatListExample.tsx    From react-native-scroll-bottom-sheet with MIT License 5 votes vote down vote up
HorizontalFlatListExample: React.FC<Props> = ({ navigation }) => {
  const bottomSheetRef = React.useRef<ScrollBottomSheet<any> | null>(null);

  const animatedPosition = React.useRef(new Value(0));
  const opacity = interpolate(animatedPosition.current, {
    inputRange: [0, 1],
    outputRange: [0, 0.75],
    extrapolate: Extrapolate.CLAMP,
  });

  const renderRow = React.useCallback(
    ({ index }) => <Carousel index={index} />,
    []
  );

  return (
    <View style={styles.container}>
      <MapView
        style={StyleSheet.absoluteFillObject}
        initialRegion={initialRegion}
      />
      <Animated.View
        pointerEvents="box-none"
        style={[
          StyleSheet.absoluteFillObject,
          { backgroundColor: 'black', opacity },
        ]}
      />
      <View style={StyleSheet.absoluteFillObject} pointerEvents="box-none">
        <TouchableRipple
          style={[styles.iconContainer, { right: 16 }]}
          onPress={() => {
            bottomSheetRef.current?.snapTo(2);
          }}
          borderless
        >
          <MaterialCommunityIcons
            name="close"
            size={32}
            color="white"
            style={styles.icon}
          />
        </TouchableRipple>
        {Platform.OS === 'ios' && (
          <TouchableRipple
            style={[styles.iconContainer, { left: 16 }]}
            onPress={() => {
              navigation.goBack();
            }}
            borderless
          >
            <Ionicons
              name="ios-arrow-back"
              size={32}
              color="white"
              style={styles.icon}
            />
          </TouchableRipple>
        )}
      </View>
      <ScrollBottomSheet<string>
        ref={bottomSheetRef}
        componentType="FlatList"
        topInset={24}
        animatedPosition={animatedPosition.current}
        snapPoints={snapPointsFromTop}
        initialSnapIndex={2}
        renderHandle={() => <Handle />}
        keyExtractor={i => `row-${i}`}
        initialNumToRender={5}
        contentContainerStyle={styles.contentContainerStyle}
        data={Array.from({ length: 100 }).map((_, i) => String(i))}
        renderItem={renderRow}
      />
    </View>
  );
}
Example #12
Source File: Footer.tsx    From make-a-fortune with MIT License 5 votes vote down vote up
export default function Footer(): JSX.Element {
  const [selected, setSelected] = React.useState(1);
  return (
    <HStack justifyContent="center" safeAreaBottom mb={1}>
      <Pressable py={3} flex={1} onPress={() => setSelected(0)}>
        <Center>
          {selected === 0 ? (
            <Icon
              as={<MaterialCommunityIcons name="home" />}
              color="black"
              size="sm"
            />
          ) : (
            <Icon
              as={<MaterialCommunityIcons name="home-outline" />}
              color="gray"
              size="sm"
            />
          )}
        </Center>
      </Pressable>
      <Pressable py={3} flex={1} onPress={() => setSelected(1)}>
        <Center>
          {selected === 1 ? (
            <Icon
              as={<MaterialCommunityIcons name="bell" />}
              color="black"
              size="sm"
            />
          ) : (
            <Icon
              as={<MaterialCommunityIcons name="bell-outline" />}
              color="gray"
              size="sm"
            />
          )}
        </Center>
      </Pressable>
      <Pressable py={3} flex={1} onPress={() => setSelected(2)}>
        <Center>
          {selected === 2 ? (
            <Icon
              as={<MaterialCommunityIcons name="account" />}
              color="black"
              size="sm"
            />
          ) : (
            <Icon
              as={<MaterialCommunityIcons name="account-outline" />}
              color="gray"
              size="sm"
            />
          )}
        </Center>
      </Pressable>
    </HStack>
  );
}
Example #13
Source File: BottomTabNavigator.tsx    From TwitterClone with MIT License 5 votes vote down vote up
function HomeNavigator() {

  const [user, setUser] = useState(null);

  useEffect(() => {
    // get the current user
    const fetchUser = async () => {
      const userInfo = await Auth.currentAuthenticatedUser({ bypassCache: true });
      if (!userInfo) {
        return;
      }

      try {
        const userData = await API.graphql(graphqlOperation(getUser, { id: userInfo.attributes.sub }))
        if (userData) {
          setUser(userData.data.getUser);
        }
      } catch (e) {
        console.log(e);
      }
    }
    fetchUser();
  }, [])

  return (
    <TabOneStack.Navigator>
      <TabOneStack.Screen
        name="HomeScreen"
        component={HomeScreen}
        options={{
          headerRightContainerStyle: {
            marginRight: 15,
          },
          headerLeftContainerStyle: {
            marginLeft: 15,
          },
          headerTitle: () => (
            <Ionicons name={"logo-twitter"} size={30} color={Colors.light.tint}/>
          ),
          headerRight: () => (
            <MaterialCommunityIcons name={"star-four-points-outline"} size={30} color={Colors.light.tint}/>
          ),
          headerLeft: () => (
            <ProfilePicture size={40} image={user?.image} />
          )
        }}
      />
    </TabOneStack.Navigator>
  );
}
Example #14
Source File: ThreadList.tsx    From make-a-fortune with MIT License 5 votes vote down vote up
ThreadList: React.FC<{
  safeArea?: boolean;
}> = ({ safeArea }) => {
  const [refreshing, setRefreshing] = useState(false);

  const reloadLines = React.useCallback(() => {
    setRefreshing(true);

    wait(2000).then(() => {
      setRefreshing(false);
    });
  }, []);

  return (
    <>
      <Box safeAreaTop={safeArea} />
      <FlatList
        removeClippedSubviews
        refreshControl={
          <RefreshControl refreshing={refreshing} onRefresh={reloadLines} />
        }
        initialNumToRender={5}
        data={data}
        my={safeArea ? 12 : undefined}
        renderItem={({ item }) => (
          <VStack
            borderColor="gray.100"
            borderTopWidth={1}
            py={4}
            px={3}
            alignSelf="center"
            width={700}
            maxWidth="100%"
            key={item.id}
            space={1}
            bgColor="white"
          >
            <HStack space={2} alignItems="center">
              <Badge>#23333</Badge>
              <Badge>校园</Badge>
              <Box mx="auto" />
              <HStack space={1}>
                <Icon
                  as={<MaterialCommunityIcons name="comment-outline" />}
                  color="black"
                  size="xs"
                />
                <Text alignSelf="flex-end" fontSize="sm">
                  1
                </Text>
              </HStack>
            </HStack>
            <HStack space={1} alignItems="center">
              <Text>{item.title}</Text>
            </HStack>
            <Text>{item.content}</Text>
          </VStack>
        )}
        keyExtractor={item => item.id.toString()}
        // ListHeaderComponent={
        //   <Box alignSelf="center">
        //     <Button
        //       startIcon={
        //         <Icon as={MaterialCommunityIcons} name="refresh" size={5} />
        //       }
        //     >
        //       有新帖子
        //     </Button>
        //   </Box>
        // }
      />
      <Box safeAreaBottom={safeArea} />
    </>
  );
}
Example #15
Source File: GameLoader.tsx    From tic-tac-toe-app with MIT License 4 votes vote down vote up
GameLoader: React.FC<Props> = ({ styles }) => {
    const theme = useSelector(selectTheme);
    const hapticsEnabled = useSelector(selectHaptics);
    const game = useSelector(selectGame);

    const dispatch = useDispatch();

    const { playerId, lobbyId } = game;

    const { width, height } = useDimensions().window;

    const disconnectPlayer = async () => {
        try {
            const docRef = firestore.collection('lobbies').doc(lobbyId);
            const getGameState = await docRef.get();

            const gamePlayers = getGameState.data()?.players as
                | Player[]
                | undefined;
            if (!gamePlayers) return;

            const players = modifyPlayer(gamePlayers, playerId, {
                connected: false,
            });

            await docRef.set({ players }, { merge: true });

            dispatch(quitGame());
        } catch (err) {
            showError();
            handleError(err);
        }
    };

    const connectPlayer = async () => {
        try {
            const docRef = firestore.collection('lobbies').doc(lobbyId);

            const players = modifyPlayer(game.players, playerId, {
                connected: true,
            });
            await docRef.set({ players }, { merge: true });
        } catch (err) {
            showError();
            handleError(err);
        }
    };

    const showError = () => {
        showToast('Could not connect to game server');
        dispatch(quitGame());
    };

    useEffect(() => {
        game.gameLoaded && connectPlayer();
    }, [game.gameLoaded]);

    useEffect(() => {
        const docRef = firestore.collection('lobbies').doc(lobbyId);
        let initial = true;
        const channel = docRef.onSnapshot(
            snapshot => {
                if (!snapshot.exists) return showError();

                if (initial) {
                    dispatch(
                        setGameLoaded({
                            lobbyId,
                            ...snapshot.data(),
                        })
                    );
                    initial = false;
                    return;
                }
                dispatch(
                    setGameStateChange({
                        lobbyId,
                        ...snapshot.data(),
                    } as GameState)
                );
            },
            err => {
                showError();
            }
        );

        return () => {
            disconnectPlayer();
            channel();
        };
    }, [lobbyId]);

    const connectedPlayers = useMemo(() => {
        const result = game.players ? getConnectedPlayers(game.players) : [];

        return result;
    }, [game.players]);

    const copyLobbyId = () => {
        showToast('Copied Lobby ID to Clipboard');
        Clipboard.setString(lobbyId);
        if (Platform.OS === 'ios' && hapticsEnabled) {
            Haptics.notificationAsync('success' as any);
        }
    };

    return (
        <>
            <View
                style={{
                    flexDirection: 'row',
                    alignItems: 'center',
                    justifyContent: 'center',
                }}
            >
                <Text style={styles.joinText}>Lobby ID:</Text>
                <TouchableOpacity onPress={copyLobbyId}>
                    <View style={{ flexDirection: 'row' }}>
                        <Text style={styles.lobbyId}> {lobbyId}</Text>
                        <MaterialCommunityIcons
                            color={colors[theme].text}
                            name="clipboard-text-outline"
                            style={{
                                marginLeft: calcFromWidth(2, width),
                                marginTop: calcFromHeight(12, height),
                            }}
                            size={30}
                        />
                    </View>
                </TouchableOpacity>
            </View>

            <Text style={styles.text}>
                You are player: {getPlayerName(playerId)}
            </Text>

            <GameCanvasWithSpinner
                msg="Waiting for other player..."
                loading={connectedPlayers.length < 2}
            />
            <Button
                mode="contained"
                style={styles.quitButton}
                labelStyle={{ color: 'white' }}
                onPress={() => {
                    if (Platform.OS === 'ios' && hapticsEnabled)
                        Haptics.selectionAsync();
                    disconnectPlayer();
                }}
            >
                Quit Game
            </Button>
        </>
    );
}
Example #16
Source File: PlayerMenu.tsx    From tic-tac-toe-app with MIT License 4 votes vote down vote up
PlayerMenu: React.FC<Props> = ({
    styles,
    textInput,
    setTextInput,
    handleInputChange,
    gridSize,
    handleGridSizeChange,
    handleNewGame,
    handleJoinGame,
}) => {
    const theme = useSelector(selectTheme);
    const hapticsEnabled = useSelector(selectHaptics);

    const { width, height } = useDimensions().window;

    const insertFromClipboard = async () => {
        try {
            const text = await Clipboard.getStringAsync();
            if (Boolean(text.length)) {
                showToast('Inserted text from Clipboard');
                setTextInput(text);
                if (Platform.OS === 'ios' && hapticsEnabled)
                    Haptics.notificationAsync('success' as any);
            } else {
                showToast('Clipboard is empty');
                if (Platform.OS === 'ios' && hapticsEnabled)
                    Haptics.notificationAsync('error' as any);
            }
        } catch (err) {
            handleError(err);
        }
    };

    const clearInput = () => {
        setTextInput('');
        if (Platform.OS === 'ios' && hapticsEnabled) Haptics.selectionAsync();
        Toast.hide;
    };

    return (
        <View>
            <View style={{ marginBottom: calcFromHeight(15, height) }}>
                <Text style={styles.text}>Grid Size:</Text>
                <ToggleButton.Row
                    style={{ justifyContent: 'center' }}
                    onValueChange={handleGridSizeChange}
                    value={gridSize.toString()}
                >
                    <ToggleButton
                        activeOpacity={0.6}
                        underlayColor={colors[theme].text}
                        color={
                            gridSize === 3
                                ? colors[theme].bg
                                : colors[theme].text
                        }
                        style={
                            gridSize === 3
                                ? styles.buttonGroupSelected
                                : styles.buttonGroup
                        }
                        icon="numeric-3"
                        value="3"
                    />
                    <ToggleButton
                        activeOpacity={0.6}
                        underlayColor={colors[theme].text}
                        color={
                            gridSize === 4
                                ? colors[theme].bg
                                : colors[theme].text
                        }
                        style={
                            gridSize === 4
                                ? styles.buttonGroupSelected
                                : styles.buttonGroup
                        }
                        icon="numeric-4"
                        value="4"
                    />
                    <ToggleButton
                        activeOpacity={0.6}
                        underlayColor={colors[theme].text}
                        color={
                            gridSize === 5
                                ? colors[theme].bg
                                : colors[theme].text
                        }
                        style={
                            gridSize === 5
                                ? styles.buttonGroupSelected
                                : styles.buttonGroup
                        }
                        icon="numeric-5"
                        value="5"
                    />
                </ToggleButton.Row>
            </View>
            <Button
                onPress={() => {
                    handleNewGame();
                    if (Platform.OS === 'ios' && hapticsEnabled)
                        Haptics.selectionAsync();
                }}
                mode="contained"
                style={styles.button}
                labelStyle={{ color: 'white' }}
                contentStyle={{ margin: 10 }}
            >
                New Game
            </Button>

            <View
                style={{
                    marginLeft: calcFromWidth(10, width),
                    marginRight: calcFromWidth(10, width),
                    marginTop: calcFromHeight(10, height),
                    borderBottomColor: theme === 'dark' ? 'grey' : 'lightgrey',
                    borderBottomWidth: 2,
                }}
            />

            <Text style={styles.joinText}>Join Game:</Text>

            <TextInput
                style={[
                    styles.input,
                    Platform.OS === 'web' ? { outlineWidth: 0 } : null,
                ]}
                value={textInput}
                onChangeText={handleInputChange}
                keyboardAppearance={theme}
                selectionColor={colors[theme].main}
                placeholder="Enter lobby id"
                placeholderTextColor="white"
                autoCapitalize="none"
                underlineColorAndroid="transparent"
            />

            <View
                style={{
                    flexDirection: 'row',
                    justifyContent: 'space-evenly',
                    alignItems: 'center',
                }}
            >
                {Platform.OS !== 'web' ? (
                    <>
                        <TouchableOpacity onPress={insertFromClipboard}>
                            <MaterialCommunityIcons
                                color={colors[theme].text}
                                name="clipboard-text-outline"
                                size={30}
                            />
                        </TouchableOpacity>

                        <TouchableOpacity
                            onPress={clearInput}
                            disabled={!Boolean(textInput.length)}
                        >
                            <MaterialCommunityIcons
                                color={
                                    !Boolean(textInput.length)
                                        ? 'grey'
                                        : colors[theme].text
                                }
                                name="backspace-outline"
                                size={30}
                            />
                        </TouchableOpacity>
                    </>
                ) : null}
            </View>

            <Button
                disabled={!textInput.length}
                onPress={handleJoinGame}
                mode="contained"
                style={
                    Boolean(textInput.length)
                        ? styles.button
                        : [
                              styles.button,
                              { backgroundColor: colors[theme].disabledButton },
                          ]
                }
                labelStyle={{ color: 'white' }}
                contentStyle={{ margin: 10 }}
            >
                Join
            </Button>
        </View>
    );
}
Example #17
Source File: OnlineMultiplayer.tsx    From tic-tac-toe-app with MIT License 4 votes vote down vote up
OnlineMultiplayer: React.FC = () => {
    const [textInput, setTextInput] = useState('');
    const [gridSize, setGridSize] = useState<GridNumber>(3);
    const [connected, setConnected] = useState(false);

    const theme = useSelector(selectTheme);
    const hapticsEnabled = useSelector(selectHaptics);
    const lobbyId = useSelector(selectLobbyId);

    const dispatch = useDispatch();

    useEffect(() => {
        let unsubscribe: any;
        if (Platform.OS !== 'web') {
            unsubscribe = NetInfo.addEventListener(state => {
                setConnected(state.isConnected);
            });
        }
        return () => {
            if (Platform.OS !== 'web') {
                unsubscribe();
            }
        };
    }, []);

    const { height } = useDimensions().window;

    const styles = getStyleSheet(theme, height);

    const [loading, setLoading] = useState(false);
    const handleNewGame = async () => {
        setLoading(true);
        try {
            const response = await Axios({
                method: 'POST',
                url: `${urls.gameUrl}/new`,
                data: { gameSize: gridSize },
            });

            const { data } = response;

            dispatch(setPlayerId(0));
            dispatch(setLobbyId(data.lobbyId));
        } catch (err) {
            handleError(err);
        }
        setLoading(false);
    };

    const handleJoinGame = async () => {
        try {
            // Fetching lobby from text input
            const snapshot = await firestore
                .collection('lobbies')
                .doc(textInput)
                .get();

            // Checking if lobby exists
            if (!snapshot.exists) {
                if (Platform.OS === 'ios' && hapticsEnabled) {
                    Haptics.notificationAsync('error' as any);
                }
                showToast('This lobby does not exist...');
                return;
            }

            const players = snapshot?.data()?.players;
            const connectedPlayers = getConnectedPlayers(players);
            const playerId = players[0].connected
                ? 1
                : players[1].connected
                ? 0
                : 0;

            if (connectedPlayers.length >= 2) {
                if (Platform.OS === 'ios' && hapticsEnabled) {
                    Haptics.notificationAsync('error' as any);
                }

                showToast('Lobby is full...');
                return;
            }

            dispatch(setPlayerId(playerId));
            dispatch(setLobbyId(textInput));
            if (Platform.OS === 'ios' && hapticsEnabled)
                Haptics.notificationAsync('success' as any);
        } catch (err) {
            handleError(err);
        }
    };

    const handleInputChange = (text: string) => setTextInput(text);

    const handleGridSizeChange = (value: GridString) => {
        if (value) {
            if (Platform.OS === 'ios' && hapticsEnabled)
                Haptics.selectionAsync();
            setGridSize(Number(value) as GridNumber);
        }
    };

    if (connected || Platform.OS === 'web') {
        return (
            <View style={styles.container}>
                {lobbyId ? (
                    <GameLoader styles={styles} />
                ) : (
                    //No nested if, loading state passed directly to component
                    <PlayerMenuWithSpinner
                        msg="Connecting to game server"
                        loading={loading}
                        {...{
                            setTextInput,
                            styles,
                            textInput,
                            gridSize,
                            setGridSize,
                            handleGridSizeChange,
                            handleInputChange,
                            handleNewGame,
                            handleJoinGame,
                        }}
                    />
                    //No nested if, loading state passed directly to component
                )}
            </View>
        );
    } else {
        return (
            <View style={styles.container}>
                <MaterialCommunityIcons
                    color={colors[theme].text}
                    name="wifi-strength-alert-outline"
                    size={30}
                />
                <Text style={styles.text}>
                    Please check your{'\n'}network connection!
                </Text>
            </View>
        );
    }
}
Example #18
Source File: SettingsScreen.tsx    From tic-tac-toe-app with MIT License 4 votes vote down vote up
SettingsScreen: React.FC = ({}) => {
    const theme = useSelector(selectTheme);
    const hapticsEnabled = useSelector(selectHaptics);
    const systemThemeEnabled = useSelector(selectSystemTheme);

    const dispatch = useDispatch();

    const [selectedTheme, setSelectedTheme] = useState('system');

    const { height } = useDimensions().window;

    const styles = getStyleSheet(theme, height);

    useEffect(() => {
        if (systemThemeEnabled) setSelectedTheme('system');
        else setSelectedTheme(theme);
    }, [systemThemeEnabled, theme]);

    const onValueChange = (value: 'system' | ThemeMode) => {
        if (value) {
            if (Platform.OS === 'ios' && hapticsEnabled)
                Haptics.selectionAsync();
            if (value === 'system') {
                dispatch(enableSystemTheme(true));
                setSelectedTheme('system');
            }
            if (value === 'light' || value === 'dark') {
                setSelectedTheme(value);
                dispatch(setCurrentTheme(value));
                dispatch(enableSystemTheme(false));
            }
        }
    };

    const sendEmail = () => {
        try {
            if (Platform.OS === 'ios' && hapticsEnabled)
                Haptics.selectionAsync();
            Linking.openURL('mailto:[email protected]');
        } catch (err) {
            handleError(err);
        }
    };

    return (
        <View style={styles.container}>
            <Text
                style={[
                    styles.text,
                    {
                        margin: 0,
                        marginBottom: calcFromHeight(8, height),
                    },
                ]}
            >
                Theme:
            </Text>
            <ToggleButton.Row
                style={{ marginBottom: calcFromHeight(15, height) }}
                onValueChange={onValueChange as (e: string) => void}
                value={selectedTheme}
            >
                <ToggleButton
                    color={
                        selectedTheme === 'system'
                            ? colors[theme].bg
                            : colors[theme].text
                    }
                    style={
                        selectedTheme === 'system'
                            ? styles.buttonGroupSelected
                            : styles.buttonGroup
                    }
                    icon="theme-light-dark"
                    value="system"
                />
                <ToggleButton
                    color={
                        selectedTheme === 'light'
                            ? colors[theme].bg
                            : colors[theme].text
                    }
                    style={
                        selectedTheme === 'light'
                            ? styles.buttonGroupSelected
                            : styles.buttonGroup
                    }
                    icon="weather-sunny"
                    value="light"
                />
                <ToggleButton
                    color={
                        selectedTheme === 'dark'
                            ? colors[theme].bg
                            : colors[theme].text
                    }
                    style={
                        selectedTheme === 'dark'
                            ? styles.buttonGroupSelected
                            : styles.buttonGroup
                    }
                    icon="weather-night"
                    value="dark"
                />
            </ToggleButton.Row>
            {Platform.OS === 'ios' && (
                <View style={styles.row}>
                    <Text style={styles.text}>Haptics:</Text>
                    <Switch
                        color={colors[theme].main}
                        value={hapticsEnabled}
                        onValueChange={() =>
                            dispatch(enableHaptics(!hapticsEnabled))
                        }
                    />
                </View>
            )}

            <View>
                <Text style={styles.header}>About the App:</Text>
                <Text
                    style={[
                        styles.text,
                        { marginBottom: calcFromHeight(15, height) },
                    ]}
                >
                    Developed by:
                </Text>
                <View style={styles.row}>
                    <TouchableOpacity
                        onPress={() => openLink(urls.andorGithub)}
                    >
                        <Text style={styles.textAuthor}>Andor Davoti</Text>
                    </TouchableOpacity>
                    <Text
                        style={[
                            styles.text,
                            {
                                marginBottom: calcFromHeight(15, height),
                                margin: calcFromHeight(4, height),
                            },
                        ]}
                    >
                        &#38;{' '}
                    </Text>

                    <TouchableOpacity
                        onPress={() => openLink(urls.sannaGithub)}
                    >
                        <Text style={styles.textAuthor}>Sanna Jammeh</Text>
                    </TouchableOpacity>
                </View>

                <TouchableOpacity
                    style={[
                        styles.row,
                        { marginBottom: calcFromHeight(15, height) },
                    ]}
                    onPress={() => openLink(urls.projectGithub)}
                >
                    <MaterialCommunityIcons
                        color={colors[theme].text}
                        name="github-circle"
                        size={25}
                    />
                    <Text style={styles.text}>Project on GitHub</Text>
                    <MaterialCommunityIcons
                        color={colors[theme].text}
                        name="github-circle"
                        size={25}
                    />
                </TouchableOpacity>
                <View
                    style={{ flexDirection: 'row', justifyContent: 'center' }}
                >
                    {Platform.OS !== 'web' && (
                        <Button
                            mode="contained"
                            style={styles.button}
                            labelStyle={{ color: 'white' }}
                            onPress={() => {
                                if (Platform.OS === 'ios' && hapticsEnabled)
                                    Haptics.selectionAsync();
                                StoreReview.requestReview();
                            }}
                        >
                            Rate App
                        </Button>
                    )}
                    <Button
                        mode="contained"
                        style={styles.button}
                        labelStyle={{ color: 'white' }}
                        onPress={sendEmail}
                    >
                        Contact us
                    </Button>
                </View>
                <Text style={styles.textVersion}>
                    Version: {Constants.manifest.version}
                </Text>
            </View>
        </View>
    );
}
Example #19
Source File: Column.tsx    From tic-tac-toe-app with MIT License 4 votes vote down vote up
Column: React.FC<Props> = ({
    winnerColumns,
    num,
    disableFields,
    fieldTypes,
    action,
    tied,
    winner,
    gridSize,
}) => {
    const [isWinnerColumn, setIsWinnerColumn] = useState(false);
    const theme = useSelector(selectTheme);

    const { width, height } = useDimensions().window;

    const size3 = height * 0.1;
    const size4 = height * 0.08;
    const size5 = height * 0.06;

    const styles = getStyleSheet(
        theme,
        gridSize,
        disableFields,
        size3,
        size4,
        size5,
        width
    );

    useEffect(() => {
        checkIfWinnerColumn();
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [winnerColumns]);

    const checkIfWinnerColumn = () => {
        if (
            (winnerColumns[0] === num ||
                winnerColumns[1] === num ||
                winnerColumns[2] === num ||
                winnerColumns[3] === num ||
                winnerColumns[4] === num) &&
            !isWinnerColumn
        ) {
            setIsWinnerColumn(true);
        } else if (winnerColumns) setIsWinnerColumn(false);
    };

    let icon;
    const currentFieldTypes = fieldTypes[num];

    if (currentFieldTypes === 'o') icon = 'circle-outline';
    else if (currentFieldTypes === 'x') icon = 'close';

    const size = gridSize === 3 ? 75 : gridSize === 4 ? 50 : 35; // making dynamic width height based on gridsize.
    return (
        <TouchableOpacity
            disabled={disableFields || Boolean(currentFieldTypes)}
            style={styles.column}
            onPress={() => {
                if (!currentFieldTypes) action(num);
            }}
        >
            {currentFieldTypes !== '' && (
                <View style={styles.container}>
                    <View style={{ width: size, height: size }}>
                        <MaterialCommunityIcons
                            style={{ textAlign: 'center' }}
                            color={
                                !isWinnerColumn
                                    ? (winner || tied) && disableFields
                                        ? 'grey'
                                        : 'white'
                                    : colors[theme].main
                            }
                            name={icon}
                            size={size}
                        />
                    </View>
                </View>
            )}
        </TouchableOpacity>
    );
}
Example #20
Source File: app.routes.tsx    From tiktok-clone with MIT License 4 votes vote down vote up
AppRoutes: React.FC = () => {
  const [home, setHome] = useState(true);

  StatusBar.setBarStyle('dark-content');

  if (Platform.OS === 'android') StatusBar.setBackgroundColor('#fff');

  if (home) {
    StatusBar.setHidden(true);
    if (Platform.OS === 'android') {
      StatusBar.setBackgroundColor('#fff');
      StatusBar.setBarStyle('light-content');
    }
  } else {
    StatusBar.setHidden(false);
  }

  return (
    <Tab.Navigator
      shifting={false}
      barStyle={{
        backgroundColor: home ? '#000' : '#fff',
      }}
      initialRouteName="Home"
      activeColor={home ? '#fff' : '#000'}
    >
      <Tab.Screen
        name="Home"
        component={Home}
        listeners={{
          focus: () => setHome(true),
          blur: () => setHome(false),
        }}
        options={{
          tabBarLabel: 'Home',
          tabBarIcon: ({ color }) => (
            <FontAwesome name="home" size={24} color={color} />
          ),
        }}
      />
      <Tab.Screen
        name="Discover"
        component={Discover}
        options={{
          tabBarLabel: 'Discover',
          tabBarIcon: ({ color }) => (
            <AntDesign name="search1" size={24} color={color} />
          ),
        }}
      />
      <Tab.Screen
        name="Live"
        component={Record}
        listeners={({ navigation }) => ({
          tabPress: e => {
            // Prevent default action
            e.preventDefault();

            // Do something with the `navigation` object
            navigation.navigate('Record');
          },
        })}
        options={{
          tabBarLabel: '',
          tabBarIcon: () => <HomeButtom home={home} />,
        }}
      />
      <Tab.Screen
        name="Inbox"
        component={Inbox}
        options={{
          tabBarLabel: 'Inbox',
          tabBarIcon: ({ color }) => (
            <MaterialCommunityIcons
              name="message-text-outline"
              size={24}
              color={color}
            />
          ),
        }}
      />
      <Tab.Screen
        name="Me"
        component={Me}
        options={{
          tabBarLabel: 'Me',
          tabBarIcon: ({ color }) => (
            <AntDesign name="user" size={24} color={color} />
          ),
        }}
      />
    </Tab.Navigator>
  );
}
Example #21
Source File: Home.native.tsx    From make-a-fortune with MIT License 4 votes vote down vote up
export default function HomeNative(): JSX.Element {
  return (
    <NativeBaseProvider>
      <NavigationContainer>
        <Tab.Navigator>
          <Tab.Screen
            name="Home"
            component={Layout}
            options={{
              headerLeft: () => (
                <Avatar size="sm" ml={5}>
                  A
                </Avatar>
              ),
              tabBarIcon: ({ color, size, focused }) => (
                <Icon
                  as={
                    <MaterialCommunityIcons
                      name={focused ? 'home' : 'home-outline'}
                    />
                  }
                  size={size}
                  color={color}
                />
              ),
              title: '首页',
              tabBarShowLabel: false,
            }}
          />
          <Tab.Screen
            name="Notification"
            component={Layout}
            options={{
              headerLeft: () => (
                <Avatar size="sm" ml={5}>
                  A
                </Avatar>
              ),
              tabBarIcon: ({ color, size, focused }) => (
                <Icon
                  as={
                    <MaterialCommunityIcons
                      name={focused ? 'bell' : 'bell-outline'}
                    />
                  }
                  size={size}
                  color={color}
                />
              ),
              title: '通知',
              tabBarShowLabel: false,
            }}
          />
          <Tab.Screen
            name="Profile"
            component={Layout}
            options={{
              headerLeft: () => (
                <Avatar size="sm" ml={5}>
                  A
                </Avatar>
              ),
              tabBarIcon: ({ color, size, focused }) => (
                <Icon
                  as={
                    <MaterialCommunityIcons
                      name={focused ? 'account' : 'account-outline'}
                    />
                  }
                  size={size}
                  color={color}
                />
              ),
              title: '我',
              tabBarShowLabel: false,
            }}
          />
        </Tab.Navigator>
      </NavigationContainer>
    </NativeBaseProvider>
  );
}