I'm trying to use the map function but I can't get it right. I have a side-bar which I want to show some icons. Here is an example without the map.
const SideBar = () => {
return (
<div className="fixed top-0 left-0 h-screen w-20 m-0 flex flex-col bg-gray-100 text-white shadow-lg">
<SideBarIcon icon={<FaFire size="30" />} />
<SideBarIcon icon={<FaPoo size="30" />} />
</div>
);
};
const SideBarIcon = ({ icon, text = "tooltip 💡"}) => (
<div className="sidebar-icon group">
{icon}
<span class="sidebar-tooltip group-hover:scale-100">{text}</span>
</div>
);
Here is an example with the map function
const SideBar = () => {
const icons = [FaFire, FaPoo];
return (
<div className="fixed top-0 left-0 h-screen w-20 m-0 flex flex-col bg-gray-100 text-white shadow-lg">
{icons.map(function(icon) {
return <SideBarIcon icon={<icon size="30"/>}/>
})}
</div>
);
};
const SideBarIcon = ({ icon, text = "tooltip 💡"}) => (
<div className="sidebar-icon group">
{icon}
<span class="sidebar-tooltip group-hover:scale-100">{text}</span>
</div>
);
Can you tell me what I'm doing wrong? Thank you for your time!
{icons.map(function (Icon) {
return <SideBarIcon icon={<Icon size="30"/>}/>
})}
Components start with capital letters, just change icon to Icon.
Please do not forget to use key prop for your mapped items.
https://reactjs.org/docs/jsx-in-depth.html#user-defined-components-must-be-capitalized
By simply putting icon inside the tags, it thinks you're rendering an HTML element called icon, therefore it's not rendering the mapped item. It also wouldn't work if you set it as <{icon}/>, because it would be trying to render an empty element.
Luckily, there's an easy fix -- Just capitalize Icon, and React will render it as a JSX Component.
{icons.map(function(Icon) {
return <SideBarIcon icon={<Icon size="30"/>}/>
})}
const SideBar = () => {
const icons = [<FaFire size="30" />, <FaPoo size="30" />];
return (
<div className="fixed top-0 left-0 h-screen w-20 m-0 flex flex-col bg-gray-100 text-white shadow-lg">
{icons.map(function(icon) {
return <SideBarIcon icon={icon}/>
})}
</div>
);
};