Reputation: 453
I build a custom FlatList , because my View is the same and i dont want to duplicate code.
I exec the flat list like this:
<FlatListPicker
data={availableMeetings}
type="days"
updateSelect={selectHandler}
selected={selectedDay}
/>
<FlatListPicker
data={availableMeetings[0].hours}
type="hours"
updateSelect={selectHandler}
selected={selectedHour}
/>
The custom flat list look like this:
const FlatListPicker = ({ data, type, updateSelect, selected }) => {
return (
<FlatList
horizontal={true}
data={data}
renderItem={({ item }) => (
<TouchableOpacity
style={[
styles.button,
selected === item.key && styles.buttonselected,
]}
onPress={() => updateSelect(item.key, type)}
>
<Text
style={[
styles.daytext,
selected === item.key && styles.textselected,
]}
>
{item.dayName}
{"\n"}
{type === "days" ? (
<Text style={styles.datetext}>{item.date}</Text>
) : (
<Text style={styles.datetext}>{item}</Text>
)}
</Text>
</TouchableOpacity>
)}
keyExtractor={(item, index) => index.toString()}
/>
);
};
Everything working good. but like you see i need to pass prop called "Type" to decide what to show in the component, (because otherwise objects Item is different and i cant access to the properties of the objects), so its look little bit weird, for example:
{type === "days" ? (
<Text style={styles.datetext}>{item.date}</Text>
) : (
<Text style={styles.datetext}>{item}</Text>
)}
My question: there is a way to access dynamically to item properties ?
Upvotes: 0
Views: 319
Reputation: 596
There is a duplicatio of your code my bro the best approach to do so with tornary operator:
const FlatListPicker = ({ data, type = "days", updateSelect, selected }) => {
return (
<FlatList
horizontal={true}
data={data}
renderItem={({ item }) => (
<TouchableOpacity
style={[
styles.button,
selected === item.key && styles.buttonselected,
]}
onPress={() => updateSelect(item.key, type)}
>
<Text
style={[
styles.daytext,
selected === item.key && styles.textselected,
]}
>
{item.dayName}
{"\n"}
<Text style={styles.datetext}>{type === "days" ? item.date : item }</Text>
</Text>
</TouchableOpacity>
)}
keyExtractor={(item, index) => index.toString()}
/>
);
};
Upvotes: 0
Reputation: 3636
you can use javascript logical operator
try this
<Text style={styles.datetext}>{item.date || item}</Text>
Upvotes: 1