Reputation:
I'm using material-ui icons, and I would like to add a different icon for each array object shown below. Without manually adding a style property to each object icon in the array, how do I add the "iconStyle" to each object in the array?
import Icon1 from "material-ui/icons"
import Icon2 from "material-ui/icons"
//if i have an array like this:
const array = [
{name: "test1", icon: <Icon1/>}, //material ui icon1
{name: "test2", icon: <Icon2/>}, //material ui icon2
]
//and i map through it like this:
const txtStyle = {//css};
const iconStyle = {//css}
<div>
{array.map(arr => {
return <div>
<p style={txtStyle}>{arr.name}</p>
{arr.icon} // how do i add the iconStyle to this element?
</div>
})}
</div>
// how do i add the iconStyle object to the person.icon without adding it manually to each icon in the array?
//not like this:
const array = [
{name: "test1", icon: <Icon1 style={iconStyle}/>}, //material ui icon1
{name: "test2", icon: <Icon2 style={iconStyle}/>}, //material ui icon2
]
Any feedback/help would be appreciated!
Upvotes: 1
Views: 1336
Reputation:
import Icon1 from "material-ui/icons"
import Icon2 from "material-ui/icons"
import { SvgIcon } from "@material-ui/core"; //import SvgIcon
const array = [
{name: "test1", icon: Icon1}, //remove tags
{name: "test2", icon: Icon2},
]
<div>
{array.map(arr => { //use component and svg icon
return <div>
<p style={txtStyle}>{arr.name}</p>
<SvgIcon component={arr.icon} className="whateverclassyouwant"/>
</div>
})}
</div>
Upvotes: 1
Reputation: 5380
Just you can take only reference of the icon component then render it in array.map
const array = [
{name: "test1", icon: Icon1}, // attention on this line
{name: "test2", icon: Icon2},
]
const txtStyle = {};
const iconStyle = {};
return (
<div>
{array.map(arr => (
<div>
<p style={txtStyle}>{arr.name}</p>
<arr.icon style={iconStyle}/>
</div>
)}
</div>
)
Upvotes: 1
Reputation: 3772
there are two ways to do that.
Make your icons
accepts the props
const arr = [
{ name: "Circle", Icon: (props) => <Icon1 {...props} /> },
{ name: "Shopping", Icon: (props) => <Icon2 {...props} /> }
];
Now the style object can be passed as a regular prop to the icons.
<div>
{arr.map((item) => (
<>
<p style={txtStyle}>{item.name}</p>
<item.Icon style={iconStyle}/>
</>
))}
</div>
If you're using makeStyles
to add the styles then you can add a class to the container div
and then target the icon from that container rule.
export default function App() {
const classes = useStyles();
return (
<Box>
{arr1.map((item) => (
<div className={classes.iconDiv}>
<p>{item.name}</p>
{item.icon}
</div>
))}
</Box>
);
}
const useStyles = makeStyles((theme) => ({
iconDiv: {
"&>p": {
color: "red"
},
"&>svg": {
color: "green",
cursor: "pointer"
}
}
}));
in this method, there's no need to change the arr
array.
Here is a working example of both methods...
Upvotes: 0