I have a dynamic number of arrays like [1,2,3,5,7], [1,2,3], [2,7,8] ... where the elements represent a platform id which helps to identify platforms like PlayStation, Xbox etc. uniquely...
I want to link a react-icon to each element of the array such that each symbol gets linked to the id of the platform it represents, for eg:
if platform id of playstation is 2 i want <FaPlaystation/> icon linked to it so that i can display it in my react card component, basically something like this:

how do i implement this in react? I'm getting platform ids via a prop called plat, upon iterating it like this :
let platMain = plat.map(plat=>plat.platform.id);
i get the array of ids
You can create a Map (not to be confused with Array.prototype.map()) to be later used to lookup the associated icon component by the numeric key provided.
import { FaAndroid, FaAngular, FaReact, FaDev } from "react-icons/fa";
const map1 = new Map([
[1, FaAndroid],
[2, FaAngular],
[3, FaReact],
[4, FaDev]
]);
const platMain = [2, 3, 4, 5, 6, 7];
export default function App() {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
{platMain.map((key) => {
const icon = map1.get(key);
return icon ? icon() : null;
})}
</div>
);
}
Or similar with a plain old Object with numeric keys.
import { FaAndroid, FaAngular, FaReact, FaDev } from "react-icons/fa";
const map = {
1: FaAndroid,
2: FaAngular,
3: FaReact,
4: FaDev
};
const platMain = [2, 3, 4, 5, 6, 7];
export default function App() {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
{platMain.map((key) => {
const icon = map[key];
return icon ? icon() : null;
})}
</div>
);
}
You can do like this
// utility to get Icon
const getPlatformIcon = (platformId) => {
switch (platformId) {
case 1:
return <FaIconName />
case 2:
return <FaPlaystation/>
case 3:
return <FaAnotherIconName />
default:
return <FaDefaultIcon /> // or return null if you don't have it
}
}
// your component
export default function({plat}) {
return (
<div>
{
plat.map(p => getPlatformIcon(p.platform.id))
}
</div>
)
}
I think this method would be better:
const yourArray = [
{id: 2, icon: <FaPlaystation /> },
{id: 4, icon: <AnotherIcon />},
{id: 6, icon: <AnotherIcon />}
]
//then
{yourArray.map((item)=>(
<div>
<p>item.id</p>
{item.icon}
</div>
))}