First of all we need to know what “selecting an item” means. It comprises of two properties –
- Change of visual of selected item from non-selected items.
- Keeping track of selected item by storing it’s metadata in some variable.
In this article we will write a code to select an item from flatlist in React Native.
Code Example
import React, { useState } from "react"; import { FlatList, SafeAreaView, StyleSheet, Text, TouchableOpacity } from "react-native"; const SUPERHERO_DATA = [ { id: '1', title: 'Ironman', }, { id: '2', title: 'Thor', }, { id: '3', title: 'Captain America', }, ]; const Item = ({ item, onPress, backgroundColor, textColor }) => ( <TouchableOpacity onPress={onPress} style={[styles.item, backgroundColor]}> <Text style={[styles.title, textColor]}>{item.title}</Text> </TouchableOpacity> ); const App = () => { const [selectedId, setSelectedId] = useState(null); const renderItem = ({ item }) => { const backgroundColor = item.id === selectedId ? "#6e3b6e" : "#fff000"; const color = item.id === selectedId ? 'white' : 'black'; return ( <Item item={item} onPress={() => setSelectedId(item.id)} backgroundColor={{ backgroundColor }} textColor={{ color }} /> ); }; return ( <SafeAreaView style={styles.container}> <FlatList data={SUPERHERO_DATA} renderItem={renderItem} keyExtractor={(item) => item.id} extraData={selectedId} /> </SafeAreaView> ); }; const styles = StyleSheet.create({ container: { flex: 1, }, item: { backgroundColor: '#fff000', padding: 10, marginVertical: 8, marginHorizontal: 16, }, title: { fontSize: 18, }, }); export default App;
The output will look like this –
As I mentioned in the beginning of the article, a selected item can be implemented by a strategy for visual and storing metadata.
To make items pressable for selection, we are using <TouchableOpacity>
component. On the press of an item, we are storing it’s id using a state variable, selectedId
and change background & text colors.
If you are creating a single choice list where user can select a list item and later you could pass the value to next page, then you can simply use the state variable value.
Another important thing to notice is that we are using extraData
props in FlatList
at line 48. This holds any value like array, string, number etc. The purpose is to indicate flatlist that a re-render is required.
FlatList is a PureComponent which needs to know when to re-render. Since our data is not changing with selection, so flatlist won’t re-render. Hence extraData
props is provided. If the value of this props changes, the list re-renders. That’s why we are passing the selected element’s id to it.
Live Demo
Conclusion
So we saw how a single item selection works in flatlist in React Native. In the next article we will use this technique to select multiple items in the list.
Read These Next ⬇️
How to Create a Simple List?
How to Select Single Item from List?
How to Select Multiple Items from List?
How to add Separator between list items?
How to create Multiple columns List?
How to Create Placeholder Message in Empty List?
How to Add Footer to the List?
How to Add Header to the List?
How to create Horizontal List?
How to create Inverted List?
How to create Pull to Refresh in List?
How to create Infinite Loading List?
How to create Section List?
React Native Series
Alert
- Basic Alert
- Dismiss on Clicking Outside
- Input Fields in Alert Dialog – Prompt()
- Dark-Light Theme of Dialog
ActivityIndicator
- Basic Circular Loader
- Change size of Circular Loader
- Show/hide Circular Loader
- Change color of Circular Loader
Button
FlatList
- Simple List
- Single Item Selection from List
- Multiple Item Selection from List
- Adding separator between list items
- Multiple columns List
- Showing Message in Empty List
- Add Footer to the List
- Add Header to the List
- Horizontal List
- Inverted List
- Pull to Refresh in List
- Infinite Loading List
SectionList
ScrollView
- ScrollView
- Stick Single Item at Header
- Stick Multiple Items at Header
- Stick Item at Footer
- Hide Sticky Element on Scroll
Image
- Display Image from remote url
- Display local storage image
- Display Base64 Image
- Display Gif & Webp Images
- Adding Blur to Image
- Displaying loader for Image
- Resizemode for Images
- Setting Default Placeholder Image
- Background Image
Modal
RefreshControl
- RefreshControl
- Change Refresh Loader Color
- Change Refresh Loader Size
- Change Refresh Loader Background Color
- Title under Refresh Loader
- Change color of title under refresh loader
StatusBar
- Get StatusBar Size
- Change StatusBar Background Color
- Display StatusBar icons & text in While Color
- Display StatusBar icons & text in Dark Color
- Hiding StatusBar
- Translucent StatusBar
Switch
Text
- Adding Text
- Bold Text
- Italic Text
- Underline Text
- Selecting Text for copy-paste
- Changing Highlight Color of Text Selection
- Fit text in View box
- Clickable anchors in text
- Truncate Lengthy Text
TextInput
- Simple Input Field
- Auto Capitalize Text in Input Field
- Multiline Input Field
- Hide Cursor in Input Field
- Clear input Field using X
- Clear input Field when focused
- Change Cursor Color in Input Field
- Disable input field
- Icon at the left of Input Field
- Dark-Light Keyboard
- Avoid Overlapping of Keyboard
- Limiting Characters in Input Field
- Numeric Keyboard
- Email Id Keyboard
- Phone number Keyboard
- Url Keyboard
- Placeholder in input field
- Placeholder Color in Input Field
- Password Input Field
- Programmatically select text in Input Field
- Change Text Selection Color in Input Field
- Select Whole text in Input Field on Focus
- Write text from center in input field
- Changing underline color of input field
TouchableWithoutFeedback
TouchableHighlight
TouchableOpacity
Pressable
Appearance
AppState
ToastAndroid
Dimensions
Keyboard