1

By example, have a list component when each item have a custom icon component and set it on properties. But, how to add a class name to object into the variable?:

const items = [
    { name: "Example", icon: <Foo /> }
];

return (
    <ListItems items={items} />
)

Now, from ListItems components, how to add a classname to icon object?

return (
    <div>
        {items.map((prop, key) => {
            {prop.icon}
            <span>{prop.name}</span>
        })}
    </div>
);

The ListItem is a component with own style, but need add classname to icon object, by example:

<[prop.icon] className={classes.foo} />

(but <[prop.icon] /> is a invalid syntax).

e-info128
  • 3,727
  • 10
  • 40
  • 57
  • Have you tried <{prop.icon} className={classes.foo} /> ... I have no idea if that will work. I normally achieve this effect with {children}. – Diesel Jul 15 '20 at 02:58
  • `Line 65:30: Parsing error: Unexpected token` `<{prop.icon} />`. Yes, with `{prop.icon}` without tag works fine, but, how to add the classnames to `prop.icon` without jsx tag or how to convert the object to a valid jsx tag. – e-info128 Jul 15 '20 at 03:02
  • So you are passing a component down, and you want to display that component in the child? – Diesel Jul 15 '20 at 03:03
  • Need display the `{prop.icon}` component but with a specific class setted by the `ListItems` components. The icon is set from the main layout dinamicaly. The classnames styles is for `ListItems` not from main layout. – e-info128 Jul 15 '20 at 03:05
  • The `ListItems` is the sidebar component of the main admin panel layout, from main layout set the items with custom icons from `materials.io`, but need set the classnames of the each icon from the sidebar component to recycle component without styles dependencies from the main layout. – e-info128 Jul 15 '20 at 03:07
  • Glad you found an answer, https://stackoverflow.com/questions/39226928/react-adding-class-to-children-components is similar too – Diesel Jul 15 '20 at 03:18

2 Answers2

2

I think you might have to change your icon as a component instead a JSXElement:

icon: props => <Foo {...props} /> 

Then you can use it as a component normally:

const Icon = props.icon;
<Icon className="yourClassName" />
tmhao2005
  • 14,776
  • 2
  • 37
  • 44
1

I am not sure if its the best solution, anyway you can have it a try

const items = [
    { name: "Example", icon: (props) => <Foo {...props} /> }
];

return (
    <ListItems items={items} />
)
return (
    <div>
        {links.map((prop, key) => {
            {prop.icon({className: classes.foo})}
            <span>{prop.name}</span>
        })}
    </div>
);
lam
  • 545
  • 1
  • 3
  • 10