Adding a specific element to a map

by amani rose   Last Updated October 20, 2019 05:26 AM

I have a map fetched from database ..i want to add to every item in this array icon with different style ...This is my map in render..

{
    this.state.categories.results.map((item, key) => (
        <View key={key}>
            <Text>{item.name}</Text>
        </View>
    ))
}

i want to add for each item.name a specific Fontawesome icon so i tried to put these icons with style in another map

 const a = [
    {
        id: 1,
        icon: "car",
        style: { width: 50, fontSize: 40, height: 60, color: "#f56217" }
    },
    {
        id: 2,
        icon: "home",
        style: { width: 50, fontSize: 40, height: 60, color: "#2c3e50" }
    },
    {
        id: 3,
        icon: "tv",
        style: { width: 50, fontSize: 40, height: 60, color: "black" }
    },
]

than in render i added

<View>
    {
        a.map(i => (
            <FontAwesome name={i.icon} style={i.style} />
        ))
    }
    <View>
        {
            this.state.categories.results.map((item, key) => (
                <View key={key}>
                    <Text>{item.name}</Text>
                </View>
            ))
        }
    </View>
</View>

So there any way to add a specific element to this map without make a another map? what is the most shortened way to do this?

Tags : react-native


Answers 1


you can define several type base on item.name for example :

const CATEGORIES_TYPES = {
  car: {
    style: { width: 50, fontSize: 40, height: 60, color: '#f56217' }
  },
  home: {
    style: { width: 50, fontSize: 40, height: 60, color: '#2c3e50' }
  },
  tv: {
    icon: 'tv',
    style: { width: 50, fontSize: 40, height: 60, color: 'black' }
  }
};

then in render :

this.state.categories.results.map((item, key) => (
    <View key={key}>
      {CATEGORIES_TYPES[item.name] && (
        <FontAwesome name={item.icon} style={CATEGORIES_TYPES[item.name].style} />
      )}

      <Text>{item.name}</Text>
    </View>
  ));
Maleking
Maleking
October 19, 2019 20:19 PM

Related Questions


Updated March 18, 2017 06:26 AM

Updated November 14, 2018 04:26 AM

Updated November 22, 2017 17:26 PM

Updated April 18, 2018 17:26 PM

Updated January 10, 2018 07:26 AM