Home > Mobile >  Variable rendering while performing an action in React Native
Variable rendering while performing an action in React Native

Time:08-18

So, I am trying to get the item of a dictonary in a conditional rendering format. This is the way I tried:

const selectionDict = {
Kcal: 'items.energy',
Protein: 'items.proteins',
Carbohydrates: 'items.carbohydrates',
Fat: 'items.fat',
Overview: ''
  };

let renderCard = ({ item }) => {
    
    return(
      <View style={[styles.renderCardContainer, styles.margins]}>
        <View style={{width: '85%'}}>
          <Text numberOfLines={1} style={styles.productName}>{item.product_name}</Text>
          <Text style={styles.consumedQuantity}>
            <Text>{item.consumed_quantity}</Text>
            <Text> gram</Text>
          </Text>
        </View>
        <View style={styles.energy}>
          <Text style={styles.energyText}>{selectionDict[Object.keys(selectionDict)[0]]}</Text>
        </View>
     </View>
    );
  };

---Edited---

 <FlatList
          data={retrievedData}
          keyExtractor={(item, index) => index.toString()}
          renderItem = {renderCard}
        />

However, currently I get 'item.energy' rendered, but I want to have the value of items.energy... How do I get this?

CodePudding user response:

Since the item object contains a key called energy, and you want to pick the value for this key depending on a value in selectionDict, I would change selectionDict to the following.

const selectionDict = {
    Kcal: 'energy',
    Protein: 'proteins',
    Carbohydrates: 'carbohydrates',
    Fat: 'fat',
    Overview: ''
};

Then, you can pick it as you initially wanted, but this time by accessing the item objects value for the key energy:

item[selectionDict[Object.keys(selectionDict)[0]]]

To make things clear:

Object.keys(selectionDict)[0]

returns the first key of the object selectionDict which is Kcal.

selectionDict[Object.keys(selectionDict)[0]]

picks the value for the key Kcal which I have changed to energy.

Since your item object which you provide as a parameter to your renderCard function contains a key called energy we can access it with the picked key.

item[selectionDict[Object.keys(selectionDict)[0]]]

I am not exactly sure why you have implemented it like this, since it seems rather complicated but it should work.

P.S.: Judging from the comments, I have assumed that your item object looks similar to the following.

{
    energy: 200,
}
  • Related