I'm creating a react app which lists games from a third party API. This is my card component.
In place of the textual names of platforms, i want to display icons of said platforms, for which I'm using react-icons. How can i dynamically map platform names to an icon? This is what i'm passing in the plat prop:
I'm passing the values to my card component via props:
<SearchRes
key={game.name}
title={game.name}
rating={game.metacritic}
genre={game.genres.map(genre=>genre.name+" ")}
imglnk={(game.background_image===null)?"":game.background_image}
gameid={game.id}
slug={game.slug}
plat={game.parent_platforms}
/>
I've tried this, but then the question is how can I use it dynamically, as each game will have different sets of platforms:
<p>{platform.map(icon=>icon.platform.id===4?<FaWindows key="1"/>:null)}</p>
(used this snippet when i passed the whole platform array in prop)
Edit: I tried the hashmap by implementing this:
const iconMap = {
1: <FaWindows key="1"/>,
2: <FaPlaystation key="2"/>,
3: <FaXbox key="3"/>,
4: <FaAppStoreIos key="4"/>,
5: <FaApple key="5"/>,
6: <FaLinux key="6"/>,
7: <SiNintendoswitch key="7"/>,
8: <FaAndroid key="8"/>
}
const icon = iconMap[plat.platform.id] || null;
but i'm getting this error:
TypeError: Cannot read properties of undefined (reading 'id')

A simple approach is to keep a hash map where the key will be the platform id and the value can be the React component (icon) you want to display.
Example in code:
const iconMap = {
4: <FaWindows key="1"/>,
5: <p>Hello world</p>
}
Then usage can be a simple as:
const icon = iconMap[platform.id] || null;
return (
<div className='icon-wrapper'>
{icon}
</div>
)