react-native#FlatList TypeScript Examples

The following examples show how to use react-native#FlatList. 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: EmptyScreen.tsx    From clipped-tabbar with BSD 3-Clause "New" or "Revised" License 8 votes vote down vote up
EmptyScreen: React.FC = () => {
  const colors = useMemo(() => [...new Array(20)].map(() => generateColor()), []);

  return (
    <SafeAreaView style={styles.container}>
      <FlatList
        contentContainerStyle={{
          paddingBottom: 80,
        }}
        data={colors}
        renderItem={({ item: color }) => (
          <View
            style={[styles.item, {
              backgroundColor: color
            }]}
          />
        )}
        keyExtractor={(item, idx) => `item_${idx}`}
      />
    </SafeAreaView>
  );
}
Example #2
Source File: DropList.tsx    From frontatish with MIT License 7 votes vote down vote up
DropList = (props: DropListProps) => {
  const { items, active, onChange, itemStyle } = props;
  const Colors = useColors();
  const styles = getStyles(Colors);
  const renderItem = ({ item, index }: { item: DropItem; index: number }) => {
    return (
      <TouchableOpacity onPress={() => onChange(index)}>
        <View
          style={{
            backgroundColor: active === index ? Colors.font_6 : Colors.white,
            padding: 16,
          }}
        >
          <Text style={{ color: Colors.font_2, ...itemStyle }}>
            {item?.label ?? item}
          </Text>
        </View>
        {index < items.length - 1 && <Line />}
      </TouchableOpacity>
    );
  };

  return (
    <View style={styles.listContainer}>
      <FlatList
        data={items}
        // contentContainerStyle={styles.listContainer}
        renderItem={renderItem}
        keyExtractor={(item) => item?.label ?? item}
        persistentScrollbar
      />
    </View>
  );
}
Example #3
Source File: index.tsx    From SpotifyClone with MIT License 7 votes vote down vote up
AlbumCategory = (props: AlbumCategoryProps) => (
  <View style={styles.container}>
    <Text style={styles.title}>{props.title}</Text>
    <FlatList
      data={props.albums}
      renderItem={({ item }) => <AlbumComponent album={item} />}
      keyExtractor={( item ) => item.id}
      showsHorizontalScrollIndicator={false}
      horizontal
    />
  </View>
)
Example #4
Source File: ChangeTheme.tsx    From vsinder with Apache License 2.0 7 votes vote down vote up
ChangeTheme: React.FC<ChangeThemeProps> = ({}) => {
  const [, setTheme] = useContext(ThemeContext);
  return (
    <ScreenWrapper noPadding>
      <FlatList
        data={vscodeThemes}
        keyExtractor={({ name }) => name}
        renderItem={({ item }) => {
          return <Cell onPress={() => setTheme(item.name)}>{item.name}</Cell>;
        }}
      />
    </ScreenWrapper>
  );
}
Example #5
Source File: AlbumScreen.tsx    From SpotifyClone with MIT License 6 votes vote down vote up
AlbumScreen = () => {

  const route = useRoute();
  const albumId = route.params.id;

  const [album, setAlbum] = useState(null)

  useEffect(() => {
    const fetchAlbumDetails = async () => {
      try {
        const data = await API.graphql(graphqlOperation(getAlbum, { id: albumId }))
        setAlbum(data.data.getAlbum)
      } catch (e) {
        console.log(e);
      }
    }

    fetchAlbumDetails();
  }, [])

  if (!album) {
    return <Text>Loading...</Text>
  }

  return (
    <View>
      <FlatList
        data={album.songs.items}
        renderItem={({ item }) => <SongListItem song={item} />}
        keyExtractor={(item) => item.id}
        ListHeaderComponent={() => <AlbumHeader album={album} />}
      />
    </View>
  )
}
Example #6
Source File: index.tsx    From TwitterClone with MIT License 6 votes vote down vote up
Feed = () => {

  const [tweets, setTweets] = useState([]);
  const [loading, setLoading] = useState(false);

  const fetchTweets = async () => {
    setLoading(true);
    try {
      const tweetsData = await API.graphql(graphqlOperation(listTweets));
      setTweets(tweetsData.data.listTweets.items);
    } catch (e) {
      console.log(e);
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    fetchTweets();
  }, [])

  return (
    <View style={{width: '100%'}}>
      <FlatList
        data={tweets}
        renderItem={({item}) => <Tweet tweet={item}/>}
        keyExtractor={(item) => item.id}
        refreshing={loading}
        onRefresh={fetchTweets}
        ListHeaderComponent={UserFleetsList}
      />
    </View>
  );
}
Example #7
Source File: App.tsx    From react-native-ios-context-menu with MIT License 6 votes vote down vote up
export function HomeScreen(props) {
  const renderItem: ListRenderItem<ExampleListItem>  = ({ item })  => (
    React.createElement(item.component, {
      index: item.id,
      style: styles.exampleListItem
    })
  );

  return (
    <SafeAreaView>
      {false && (
        <TouchableOpacity
          onPress={() => {
            props.navigation.navigate('Test');
          }}
        >
          <Text>
            Push
          </Text>
        </TouchableOpacity>
      )}
      <FlatList
        contentContainerStyle={styles.scrollContentContainer}
        data={EXAMPLE_ITEMS}
        renderItem={renderItem}
        keyExtractor={(item) => `item-${item.id}`}
      />
    </SafeAreaView>
  );
}
Example #8
Source File: WeekCarousel.tsx    From nyxo-app with GNU General Public License v3.0 6 votes vote down vote up
WeekCarousel: FC<Props> = ({
  ListHeaderComponent,
  refreshControl,
  coaching
}) => {
  const { data, error } = useWeeks()

  const renderWeekCard: ListRenderItem<WeekCollectionItem> = ({ item }) => {
    return (
      <WeekCard
        key={item.slug}
        week={item}
        cardMargin={cardMargin}
        cardWidth={cardWidth}
        coaching={coaching}
      />
    )
  }

  return (
    <FlatList
      ListHeaderComponent={ListHeaderComponent}
      refreshControl={refreshControl}
      keyExtractor={(item) => item.slug}
      showsHorizontalScrollIndicator={false}
      snapToAlignment="center"
      data={data?.coachingWeekCollection?.items}
      renderItem={renderWeekCard}
    />
  )
}
Example #9
Source File: Cart.component.tsx    From RNWCShop with GNU General Public License v3.0 6 votes vote down vote up
Cart = (props: Props): JSX.Element => {
  const { products, resetCart, total, handleCheckoutPress } = props;

  return (
    <>
      <View style={styles.cartOverview}>
        <View style={styles.leftCartOverview}>
          <Icon
            reverse
            name="trash-alt"
            type="font-awesome-5"
            onPress={resetCart}
          />
          <Text style={styles.textTotal}>{`Total:\n${toAmount(total)}`}</Text>
        </View>
        <Button title="Checkout" onPress={handleCheckoutPress} />
      </View>
      <FlatList
        contentContainerStyle={styles.container}
        data={products}
        renderItem={_renderProduct(props)}
        keyExtractor={(item): string => `${item.id}`}
        numColumns={2}
        ListEmptyComponent={_renderEmpty()}
      />
    </>
  );
}
Example #10
Source File: Browse.component.tsx    From react-native-woocommerce with MIT License 6 votes vote down vote up
Browse = (props: Props): JSX.Element => {
  const {
    products,
    refreshing,
    onRefresh,
    onEndReached
  } = props;

  return (
    <FlatList
      contentContainerStyle={styles.container}
      data={products}
      renderItem={_renderProduct(props)}
      keyExtractor={(item): string => `${item.id}`}
      refreshing={refreshing}
      onEndReached={onEndReached}
      onRefresh={onRefresh}
      numColumns={2}
    />
  );
}
Example #11
Source File: AllMessages.tsx    From react-native-chatapp-socket with MIT License 6 votes vote down vote up
AllMessages = () => {
    const [language, setLanguage] = useState(store.getState().AppLanguageResponse.currentLanguage.ALL_MESSAGES_SCREEN);
    useEffect(() => {
        // ComponentDidMount
        getAllMessagesList();
    }, []);
    const messages = useSelector<IRootState, any>((r_state: IRootState) => r_state.MessageResponse.all_messages);
    return (
        <View style={styles.container}>
            <Header title={language.HEADER} />
            <View style={styles.container}>
            <FlatList
                    data={messages}
                    renderItem={({ item }) => (
                        <ListItem
                            title={item.username}
                            avatarSource={'https://randomuser.me/api/portraits/lego/0.jpg'}
                            subtitle={item.last_message}
                            rightDot={item.am_i_read == 1 ? false : true}
                            onPress={() => Actions.messaging({data: item})}
                        />
                    )}
                    keyExtractor={item => item.id.toString()}
                    style={styles.flatlist}
                />
            </View>
        </View>
    );
}
Example #12
Source File: ListItem.stories.tsx    From natds-rn with ISC License 6 votes vote down vote up
Default = () => (
  <StoryContainer title="Standard">
    <FlatList
      data={data}
      renderItem={({ item }) => (
        <ListItem>
          <View style={{ padding: 16 }}>
            <TextWithTheme>{item.title}</TextWithTheme>
          </View>
        </ListItem>
      )}
    />
  </StoryContainer>
)
Example #13
Source File: flatlist.tsx    From react-native-bottomsheet-reanimated with MIT License 6 votes vote down vote up
Index = () => {
  const [listItems] = useState(dummyArray);

  const ItemView = ({ item }: { item: any }) => {
    return (
      <View style={{ width: '100%' }}>
        <Text style={styles.item}>{item.value}</Text>
      </View>
    );
  };

  const ItemSeparatorView = () => {
    return (
      //Item Separator
      <View
        style={{ height: 0.5, width: '100%', backgroundColor: '#C8C8C8' }}
      />
    );
  };

  return (
    <View style={styles.container}>
      <FlatList
        data={listItems}
        ItemSeparatorComponent={ItemSeparatorView}
        renderItem={ItemView}
        keyExtractor={(item, index) => item.id + '-' + index.toString()}
      />
    </View>
  );
}
Example #14
Source File: index.tsx    From react-native-scroll-bottom-sheet with MIT License 6 votes vote down vote up
private getScrollComponent = () => {
    switch (this.props.componentType) {
      case 'FlatList':
        return FlatList;
      case 'ScrollView':
        return ScrollView;
      case 'SectionList':
        return SectionList;
      default:
        throw new Error(
          'Component type not supported: it should be one of `FlatList`, `ScrollView` or `SectionList`'
        );
    }
  };
Example #15
Source File: CategoriesScreen.tsx    From magento_react_native_graphql with MIT License 6 votes vote down vote up
CategoriesScreen = ({
  navigation,
  route: {
    params: { categoryId },
  },
}: Props): React.ReactElement => {
  const { categories = [], loading, error } = useCategories({
    categoryId,
  });

  return (
    <GenericTemplate loading={loading} errorMessage={error?.message}>
      <FlatList
        data={categories}
        keyExtractor={item => `categoryItem${item.id.toString()}`}
        renderItem={({ item }) => (
          <CategoryListItem item={item} navigation={navigation} />
        )}
      />
    </GenericTemplate>
  );
}
Example #16
Source File: ChipList.tsx    From Covid19 with MIT License 6 votes vote down vote up
ChipList = (props: ChipListParam) => {
  const { data, selected, setSelected } = props;
  return (
    <FlatList
      style={styles.flatList}
      contentContainerStyle={styles.flatListContainer}
      data={data}
      renderItem={({ item }) => {
        return (
          <TouchableOpacity
            style={[
              styles.chipContainer,
              {
                backgroundColor: selected === item ? "#90EE90" : "white",
              },
            ]}
            onPress={() => setSelected(item)}
          >
            <Text style={styles.chipText}>{item.toLocaleUpperCase()}</Text>
          </TouchableOpacity>
        );
      }}
      horizontal
      showsHorizontalScrollIndicator={false}
    />
  );
}
Example #17
Source File: ProductList.tsx    From sellflow with MIT License 6 votes vote down vote up
export default function ProductList(props: Props) {
  let { numColumns, data, onItemPress, ...otherProps } = props;
  let itemRemainder: number = data.length % numColumns;

  return (
    <FlatList
      data={data}
      keyExtractor={(item) => item.id}
      numColumns={numColumns}
      key={numColumns}
      renderItem={({ item, index }) => {
        let productItem = (
          <ProductItem product={item} onPress={() => onItemPress(item)} />
        );
        if (index >= data.length - itemRemainder) {
          return <View style={{ flex: 1 / numColumns }}>{productItem}</View>;
        }
        return productItem;
      }}
      showsVerticalScrollIndicator={false}
      {...otherProps}
    />
  );
}
Example #18
Source File: Matches.tsx    From tinder-expo with MIT License 6 votes vote down vote up
Matches = () => (
  <ImageBackground
    source={require("../assets/images/bg.png")}
    style={styles.bg}
  >
    <View style={styles.containerMatches}>
      <View style={styles.top}>
        <Text style={styles.title}>Matches</Text>
        <TouchableOpacity>
          <Icon name="ellipsis-vertical" color={DARK_GRAY} size={20} />
        </TouchableOpacity>
      </View>

      <FlatList
        numColumns={2}
        data={DEMO}
        keyExtractor={(item, index) => index.toString()}
        renderItem={({ item }) => (
          <TouchableOpacity>
            <CardItem
              image={item.image}
              name={item.name}
              isOnline={item.isOnline}
              hasVariant
            />
          </TouchableOpacity>
        )}
      />
    </View>
  </ImageBackground>
)
Example #19
Source File: Logistic.tsx    From wuhan2020-frontend-react-native-app with MIT License 6 votes vote down vote up
function LogisticLayout() {
  const [data, , loading, refresh] = useWuhan2020<LogisticalType>('logistical');
  const [refreshing, setRefreshing] = useState(false);

  const logistics: LogisticalType[] = data || [];

  function onRefresh() {
    setRefreshing(true);
    refresh();
    wait(2000).then(() => {
      setRefreshing(false);
    });
  }

  function renderItem({ item }: { item: LogisticalType }) {
    return <Logistic item={item} />;
  }

  return (
    <StatusBarSafeLayout>
      <FlatList
        refreshControl={
          <RefreshControl
            tintColor="red"
            refreshing={refreshing}
            onRefresh={onRefresh}
          />
        }
        keyExtractor={(item: LogisticalType) => String(item.id)}
        data={logistics}
        renderItem={renderItem}
        ListFooterComponent={loading ? <Loader /> : null}
      />
    </StatusBarSafeLayout>
  );
}
Example #20
Source File: styles.ts    From gobarber-mobile with MIT License 5 votes vote down vote up
ProvidersList = styled(FlatList as new () => FlatList<Provider>)`
  padding: 32px 24px;
`
Example #21
Source File: styles.ts    From rocketseat-gostack-11-desafios with MIT License 5 votes vote down vote up
ProductList = styled(FlatList)`
  flex: 1;
  padding: 0 10px;
`
Example #22
Source File: NumPad.component.tsx    From frontatish with MIT License 5 votes vote down vote up
NumPad = (props: NumPadProps) => {
  const { onItemClick, onItemKeyClick, onSubmit, onDeleteItem } = props;
  const [actionId, setActionId] = useState(0);
  const numberRange = [
    '1',
    '2',
    '3',
    '4',
    '5',
    '6',
    '7',
    '8',
    '9',
    'X',
    '0',
    '.',
  ];

  const onButtonPress = (item: string) => {
    setActionId(actionId + 1);
    switch (item) {
      case 'X':
        // send delete meta data
        onItemKeyClick?.({
          value: item,
          actionType: 'delete',
          actionId,
        });
        // directly manipulate data on delete with this callback
        onDeleteItem?.();
        break;
      case '.':
        onSubmit();
        break;
      default:
        // send the value directly
        onItemClick?.(item);
        // send the value along with meta data
        onItemKeyClick?.({
          value: item,
          actionType: 'insert',
          actionId,
        });
        break;
    }
  };

  const Colors = useColors();
  return (
    <View>
      <FlatList
        data={numberRange}
        horizontal={false}
        scrollEnabled={false}
        numColumns={3}
        keyExtractor={(item) => item}
        renderItem={({ item }) => (
          <TouchableOpacity
            style={styles.rippleContainer}
            onPress={() => onButtonPress(item)}
          >
            {item === 'X' || item === '.' ? (
              <Icon
                name={item === 'X' ? 'backspace' : 'check'}
                color={Colors.primary}
                size={Fonts.size.h3}
              />
            ) : (
              <Text style={[styles.numberText, { color: Colors.primary }]}>
                {item}
              </Text>
            )}
          </TouchableOpacity>
        )}
      />
    </View>
  );
}
Example #23
Source File: IterableInboxMessageList.tsx    From react-native-sdk with MIT License 5 votes vote down vote up
IterableInboxMessageList = ({
   dataModel,
   rowViewModels,
   customizations,
   messageListItemLayout,
   deleteRow,
   handleMessageSelect,
   updateVisibleMessageImpressions,
   contentWidth,
   isPortrait
}: MessageListProps) => {
   const [swiping, setSwiping] = useState<boolean>(false)
   const flatListRef = useRef<FlatList>(null)

   function renderRowViewModel(rowViewModel: InboxRowViewModel, index: number, last: boolean) {
      return (
         <IterableInboxMessageCell
            key={rowViewModel.inAppMessage.messageId}
            index={index}
            last={last}
            dataModel={dataModel}
            rowViewModel={rowViewModel}
            customizations={customizations}
            swipingCheck={(swiping: boolean) => setSwiping(swiping)}
            messageListItemLayout={messageListItemLayout}
            deleteRow={(messageId: string) => deleteRow(messageId)}
            handleMessageSelect={(messageId: string, index: number) => handleMessageSelect(messageId, index)}
            contentWidth={contentWidth}
            isPortrait={isPortrait}
         />
      )
   }

   function getRowInfosFromViewTokens(viewTokens: Array<ViewToken>): Array<InboxImpressionRowInfo> {
      return viewTokens.map(
         function(viewToken) {
            var inAppMessage = IterableInAppMessage.fromViewToken(viewToken)
            
            const impression = {
               messageId: inAppMessage.messageId,
               silentInbox: inAppMessage.isSilentInbox()
            } as InboxImpressionRowInfo

            return impression
         }
      )
   }

   const inboxSessionViewabilityConfig: ViewabilityConfig = {
      minimumViewTime: 500,
      itemVisiblePercentThreshold: 100,
      waitForInteraction: false
   }

   const inboxSessionItemsChanged = useCallback((
      (info: {viewableItems: Array<ViewToken>, changed: Array<ViewToken>}) => {
         const rowInfos = getRowInfosFromViewTokens(info.viewableItems)

         updateVisibleMessageImpressions(rowInfos)
      }
   ), [])

   return (
      <FlatList
         ref={flatListRef}
         scrollEnabled={!swiping}
         data={rowViewModels}
         renderItem={({ item, index }: { item: InboxRowViewModel, index: number }) => renderRowViewModel(item, index, index === rowViewModels.length - 1)}
         keyExtractor={(item: InboxRowViewModel) => item.inAppMessage.messageId}
         viewabilityConfig={inboxSessionViewabilityConfig}
         onViewableItemsChanged={inboxSessionItemsChanged}
         onLayout={() => {flatListRef.current?.recordInteraction()}}
      />
   )
}
Example #24
Source File: index.tsx    From react-native-section-alphabet-list with MIT License 5 votes vote down vote up
ListLetterIndex: React.FC<ListLetterIndexProps> = ({
  sectionData,
  onPressLetter,
  indexContainerStyle,
  indexLetterStyle,
  indexLetterContainerStyle,
  renderCustomIndexLetter,
  letterListContainerStyle
}) => {
  const onRenderCustomIndexLetter = ({ item, index }: { item: ISectionData, index: number }) => {
    const onPress = () => onPressLetter(index)

    if (renderCustomIndexLetter) {
      return renderCustomIndexLetter({
        item,
        index,
        onPress,
      });
    }

    return (
      <TouchableOpacity testID="indexItem" onPress={onPress}>
        <View testID="indexItem__title-container" style={[styles.letterIndexItem, indexLetterContainerStyle]}>
          <Text testID="indexItem__title" style={[styles.letterIndexLabel, indexLetterStyle]}>{item.title}</Text>
        </View>
      </TouchableOpacity>
    );
  };

  return (
    <View style={[styles.letterIndexContainer, indexContainerStyle]}>
      <FlatList
        testID="flatList"
        contentContainerStyle={[styles.letterIndexList, letterListContainerStyle]}
        data={sectionData}
        keyExtractor={(i) => i.title}
        renderItem={onRenderCustomIndexLetter}
      />
    </View>
  )
}
Example #25
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 #26
Source File: simpleRefreshListScreen.tsx    From THUInfo with MIT License 5 votes vote down vote up
export function simpleRefreshListScreen<T>(
	dataSource: (props: PropsWithChildren<any>) => Promise<T[]>,
	renderItem: (
		item: T,
		refresh: () => void,
		props: PropsWithChildren<any>,
		theme: Theme,
		index: number,
		total: number,
	) => ReactElement,
	keyExtractor: (item: T) => string,
	footer?: (theme: Theme) => ReactElement,
	header?: (theme: Theme) => ReactElement,
	empty?: (theme: Theme) => ReactElement,
	initialNumToRender?: number,
): FC {
	return (props) => {
		const [data, setData] = useState<T[]>([]);
		const [refreshing, setRefreshing] = useState(false);

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

		const refresh = () => {
			setRefreshing(true);
			dataSource(props)
				.then(setData)
				.catch(() =>
					Snackbar.show({
						text: getStr("networkRetry"),
						duration: Snackbar.LENGTH_SHORT,
					}),
				)
				.then(() => setRefreshing(false));
		};
		// eslint-disable-next-line react-hooks/exhaustive-deps
		useEffect(refresh, []);

		return (
			<FlatList
				style={{flex: 1}}
				data={data}
				refreshControl={
					<RefreshControl
						refreshing={refreshing}
						onRefresh={refresh}
						colors={[theme.colors.accent]}
					/>
				}
				renderItem={({item, index}) =>
					renderItem(item, refresh, props, theme, index, data.length)
				}
				keyExtractor={keyExtractor}
				ListHeaderComponent={
					data.length === 0 ? null : header ? header(theme) : undefined
				}
				ListFooterComponent={footer ? footer(theme) : undefined}
				ListEmptyComponent={empty ? empty(theme) : undefined}
				initialNumToRender={initialNumToRender}
			/>
		);
	};
}
Example #27
Source File: RequestList.tsx    From react-native-network-logger with MIT License 5 votes vote down vote up
RequestList: React.FC<Props> = ({
  requests,
  onPressItem,
  onShowMore,
  showDetails,
}) => {
  const styles = useThemedStyles(themedStyles);

  const [searchValue, onChangeSearchText] = useState('');
  const [filteredRequests, setFilteredRequests] = useState(requests);

  useEffect(() => {
    const filtered = requests.filter((request) => {
      const value = searchValue.toLowerCase().trim();
      return (
        request.url.toLowerCase().includes(value) ||
        request.gqlOperation?.toLowerCase().includes(value)
      );
    });

    setFilteredRequests(filtered);
  }, [requests, searchValue]);

  return (
    <View style={styles.container}>
      {!showDetails && (
        <SearchBar value={searchValue} onChangeText={onChangeSearchText} />
      )}
      <FlatList
        keyExtractor={(item) => item.id}
        ListHeaderComponent={() => (
          <Button onPress={onShowMore} style={styles.more}>
            More
          </Button>
        )}
        data={filteredRequests}
        renderItem={({ item }) => (
          <ResultItem request={item} onPress={() => onPressItem(item)} />
        )}
      />
    </View>
  );
}
Example #28
Source File: PickerView.tsx    From BitcoinWalletMobile with MIT License 5 votes vote down vote up
PickerView: React.FC<Props> = (props) => {

    const languages = ["English", "Español", "Catalan", "Français", "Italiano", "Português Brasil", "日本語", "简体中文"]
    const currencies = [
        "USD",
        "AUD",
        "BRL",
        "CAD",
        "CHF",
        "CLP",
        "CNY",
        "DKK",
        "EUR",
        "GBP",
        "HKD",
        "INR",
        "ISK",
        "JPY",
        "KRW",
        "NZD",
        "PLN",
        "RUB",
        "SEK",
        "SGD",
        "THB",
        "TRY",
        "TWD",
    ]

    const getCurrentLanguage = (state: WalletState) => state.language
    const getCurrentCurrency = (state: WalletState) => state.currency

    const selectedLanguage = useSelector(getCurrentLanguage)
    const selectedCurrency = useSelector(getCurrentCurrency)

    const dispatch = useDispatch()

    const selectItem = (item: string) => {
        if (props.route.params.type == "Choose Currency") {
            dispatch(setCurrency(item))
        }
        else {
            dispatch(setLanguage(getLanguageShortCode(item)))
        }

        props.navigation.goBack()
    }

    const renderItem: ListRenderItem<string> = ({ item }) => (
        <TouchableOpacity onPress={() => { selectItem(item) }}>
            <View style={(props.route.params.type == "Choose Currency" ? (selectedCurrency == item ? styles.trSelected : styles.tr) : (selectedLanguage == getLanguageShortCode(item) ? styles.trSelected : styles.tr))}>
                <Text style={(props.route.params.type == "Choose Currency" ? (selectedCurrency == item ? styles.selectedRowText : styles.rowText) : (selectedLanguage == getLanguageShortCode(item) ? styles.selectedRowText : styles.rowText))}>{item}</Text>
                {props.route.params.type == "Choose Currency" && selectedCurrency == item &&
                    <Image style={styles.icon} source={require("../../assets/images/tick.png")} />
                }
                {props.route.params.type == "Choose Language" && selectedLanguage == getLanguageShortCode(item) &&
                    <Image style={styles.icon} source={require("../../assets/images/tick.png")} />
                }
            </View>
        </TouchableOpacity>
    )


    return (
        <View style={styles.container}>
            <Header screen={props.route.params.type == "Choose Language" ? getTranslated(selectedLanguage).choose_language : getTranslated(selectedLanguage).currency} action={() => { props.navigation.goBack() }} />
            <Screen>
                <View style={styles.container}>
                    <FlatList
                        data={props.route.params.type == "Choose Language" ? languages : currencies}
                        renderItem={renderItem}
                        showsVerticalScrollIndicator={false}
                        keyExtractor={(item) => item}
                    />
                </View>
            </Screen>
        </View>
    )
}
Example #29
Source File: AutoComplete.tsx    From react-native-paper-form-builder with MIT License 5 votes vote down vote up
function AutoComplete(props: AutoCompleteProps) {
  const {visible, setVisible, textInputProps, options, field} = props;
  const theme = useTheme();
  const styles = useMemo(
    () =>
      StyleSheet.create({
        containerStyle: {
          flex: 1,
        },
        searchStyle: {
          padding: 20,
        },
      }),
    [],
  );
  const [selectedValue, setSelectedValue] = useState(field.value);
  const [search, setSearch] = useState('');

  return (
    <Modal visible={visible} onDismiss={() => setVisible(false)}>
      <Surface style={styles.containerStyle}>
        <Appbar.Header>
          <Appbar.Action 
            testID={`${ props.textInputProps?.testID }Close`}
            icon={'close'}
            onPress={() => setVisible(false)} />
          <Appbar.Content title={textInputProps?.label} />
          <Appbar.Action
            testID={`${ props.textInputProps?.testID }Check`}
            icon={'check'}
            disabled={!selectedValue}
            onPress={() => {
              field.onChange(selectedValue);
              setVisible(false);
            }}
          />
        </Appbar.Header>
        <SafeAreaView style={styles.containerStyle}>
          <View style={styles.searchStyle}>
            <Searchbar
              testID={`${ props.textInputProps?.testID }SearchBar`}
              value={search}
              onChangeText={setSearch}
              placeholder={props.textInputProps?.placeholder ? props.textInputProps.placeholder : `Search ${ textInputProps?.label ?? "" }`}
            />
          </View>
          <FlatList
            data={options.filter(
              (option) =>
                option.label.toLowerCase().indexOf(search.toLowerCase()) !== -1,
            )}
            renderItem={({item}) => (
              <List.Item
                title={item.label}
                onPress={() => {
                  setSelectedValue(`${item.value}`);
                }}
                titleStyle={{
                  color:
                    `${item.value}` === selectedValue
                      ? theme.colors.primary
                      : theme.colors.text,
                }}
              />
            )}
            ItemSeparatorComponent={() => <Divider />}
            keyExtractor={(item) => `${item.value}`}
          />
        </SafeAreaView>
      </Surface>
    </Modal>
  );
}