Reputation: 57
I'm current designing an app that requires that requires a teacher to be picked from a given list. However, I am currently stumped on how to only allow a user to pick one item from the given FlatList, and if the user selects another item in the list, it deselects the prior selection. The app uses React-Native's FlatList component and the primary function of concern is the TeacherList component, I would really appreciate any solutions!
function ListTeacher( {id, name, selected, onSelect} ) {
return (
<View style={styles.item}>
<TouchableOpacity
style={styles.teacherName}
onPress={() => onSelect(id)}
>
<Text style={[styles.teacherName, { color: selected ? '#44B0F2' : (theme == 'dark' ? 'white' : 'black') }]}> {name} </Text>
</TouchableOpacity>
</View>
);
}
const TeacherList = (props) => {
const [selected, setSelected] = React.useState(new Map());
const onSelect = React.useCallback(
id => {
const newSelected = new Map(selected);
newSelected.set(id, !selected.get(id));
setSelected(newSelected);
},
[selected],
);
return (
<View style={styles.container}>
<FlatList
data={teachers}
keyboardShouldPersistTaps={'handled'}
renderItem={({ item }) => (
<ListTeacher
id={item.id}
name={item.name}
selected={!!selected.get(item.id)}
onSelect={onSelect}
/>
)}
keyExtractor={item => item.id}
extraData={selected}
/>
</View>
);
}```
Upvotes: 0
Views: 1103
Reputation: 281
you don't need new Map()
in this case, you just simply want to store a user choice in a variable. For example
const [selected, setSelected] = React.useState(null);
const onSelect = (id) => {
setSelected(id);
}
<ListTeacher
id={item.id}
name={item.name}
selected={item.id === selected}
onSelect={onSelect}
/>
Upvotes: 2