I am working on a mobile app to display my school's lunch options, I've parsed the data using the code below:
async function fetchData() {
fetch(apiLunchURL)
.then((response) => response.json())
.then((responseJson) => {
setJSON_DATA(responseJson);
setShowIndicator(false);
})
.catch((error) => {
console.error(error);
});
}
The code works, and my app displays this. However I'd like my title to be seperated better, here is a snippet of the JSON database I'm working with.
"type": "title",
"text": "ENTREES"
},
{
"type": "entry",
"text": "Grilled Cheese Sandwich"
},
{
"type": "entry",
"text": "Gluten-Free Grilled Cheese Sandwich"
},
{
"type": "entry",
"text": "Vegan \"Pizza\" Grilled Cheese"
},
{
"type": "title",
"text": "SIDES"
},
{
"type": "entry",
"text": "Basil Pesto Pasta Shells"
},
Right now here is the code I am using to render it:
<View style ={styles.lunchArea}>
<FlatList
data={JSON_DATA}
renderItem={({ item }) =>(
<View style={{paddingTop: 10, marginBottom: -10 }}>
<ItemRender title={item.text} />
</View>
)}
ItemSeparatorComponent={LunchDivider}
keyExtractor={item => item.id}
/>
</View>
ItemRender Code:
const ItemRender = ({ title }) => (
<View style={styles.listItem}>
<Text style={styles.lunchItems}> {title} </Text>
</View>
);
As you can see the 'title' of each section is shown by a type attribute, rather than organization im more familiar with. How can I display text using different CSS profiles, with title
being bigger and bold etc... and entry
based on the type attribute?
CodePudding user response:
Since each object contains a type
property which seems to be either title
or entry
, we could change the styling of the Text
component inside the ItemRender
component using conditional rendering. This could be implemented as follows:
renderItem={({ item }) => (
<View style={{paddingTop: 10, marginBottom: -10 }}>
<ItemRender title={item.text} type={item.type} />
</View>
)}
const ItemRender = ({ title, type }) => (
<View style={styles.listItem}>
<Text style={type === 'entry' ? styles.lunchItems : styles.title}> {title} </Text>
</View>
);
In the above, we pass the type to the ItemRender
component and conditionally change the style of the Text
component depending on whether or not type
is an entry
or not.
Here are some example styles:
const styles = StyleSheet.create({
lunchItems: {
fontSize: 12,
textAlign: 'center',
},
title: {
fontSize: 18,
fontWeight: 'bold',
textAlign: 'center',
},
});