Reputation: 105
I have a question about rendering components from object map. I have a structure like this:
const tabs = [
'tab1': {
name: 'Tab 1',
renderComponent: () => <Tab1Component />
},
'tab2': {
name: 'Tab 2',
renderComponent: () => <Tab2Component />
}
];
I want to access the renderComponent property and render sub component. Tried with function invocation, React.createElement(), doesn't work.
const MyComponent = ({tabs}) => {
const activeTab = 'tab1';
return (
<>
// How to render it?
// function invocation?
// createElement??
tabs[activeTab].renderComponent();
</>
);
};
Upvotes: 0
Views: 1593
Reputation: 71
const MyComponent = () => {
const activeTab = 'tab2';
const tabs = [
{'tab1': {
name: 'Tab 1',
renderComponent: () => <Tab1Component />
}},
{'tab2':{
name: 'Tab 2',
renderComponent: () => <Tab2Component />
}}
];
return (
<div>
{tabs.map((el) => {
if (el[activeTab]) {
return el[activeTab].renderComponent()
}
})}
</div>
); }
Upvotes: 0
Reputation: 920
Here things i guess you did wrong is
1) adding the single quotes around the object-key
2) writing key-value pairs in array without enclosing it in {}
I think you should do something like this
const tabs = [
{
tab1: {
name: 'Tab 1',
renderComponent: () => <Tab1Component />
},
tab: {
name: 'Tab 2',
renderComponent: () => <Tab1Component />
}
}
];
const activeTab = 'tab1';
and
const MyComponent = ({tabs}) => {
const activeTab = 'tab1';
return (
<>
// How to render it?
// function invocation?
// createElement??
tabs[0][activeTab].renderComponent();
</>
);
};
Upvotes: 0
Reputation: 311
Your array declaration is wrong. you should use object or array that includes objects. Try this block.
const tabs = {
tab1: {
name: "Tab 1",
renderComponent: () => <Tab1Component />
},
tab2: {
name: "Tab 2",
renderComponent: () => <Tab2Component />
}
};
Also surround your js code with {}
like;
const MyComponent= () => {
const activeTab = "tab1";
return <>{tabs[activeTab].renderComponent()}</>;
};
export default MyComponent;
Upvotes: 1