Reputation: 4755
I have an object where I store a list of components like this
const componentsToUse = {
"Key": Component,
"Key2": Component2,
}
I use which component to use like this in jsx
{array.map((obj) => (
{ React.cloneElement(componentsToUse[obj.key], obj.props)}
)}
I get an error that says
Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
If I remove cloneElement then the error goes away.
I also tried passing an element via the object like
const componentsToUse = {
"Key": <Component />,
"Key2": <Component2 />,
}
Doing so I first get an error that says propType validation failed because Component is expecting a prop which is required.
How do I solve this?
Upvotes: 1
Views: 109
Reputation: 202605
First get the component by key, and then render it as a component and pass the props to it.
{array.map((obj) => {
const Component = componentsToUse[obj.key];
return <Component {...obj.props} />;
}}
Upvotes: 1