Currently I have this situation:
export default function App() {
return (
<div className="App">
<Component1 icon={<Icon color="green" />} />
</div>
);
}
const Component1 = ({ icon }) => {
const data = [
{ name: "First", color: "green" },
{ name: "Second", color: "red" },
];
return (
<ul>
{data.map((dat, index) => (
<div key={index}>
<li>Name: {dat.name}</li>
<li>Icon: {icon}</li>
</div>
))}
</ul>
);
};
const Icon = ({ color }) => (
<div style={{ backgroundColor: color, width: 20, height: 20 }} />
);
According to this code, the Icon
will be always the same for each value of data
.
I need to pass the Icon
component to Component1
as a prop but without giving the value of the prop color
there, instead, I need to use the values that comes from data
. How can I do it?
The Icon
component can't be modified.
I wanted to do something like this:
{data.map((dat, index) => (
<div key={index}>
<li>Name: {dat.name}</li>
<li>Icon: {<icon color={dat.color} />}</li>
</div>
))}
But that won't work.
So instead of passing the Icon the way you are right now, you can pass the entire component in.
Within the app you change the Component1 call to
<Component1 IconComponent={Icon} />
With this the use of the Icon within the component becomes something like this
<IconComponent color={data.color} />
I am assuming this is simply an example and these are not all within the same file, if they are you can just call it directly without all of the passing around.
With this you are passing the component instead of a rendered instance of Icon.