i am using below code to create dynamic tabs,
var configtabs = {
ctabs: [
{
key: 31,
id: "analysis_method_tab",
title: "Analysis Method",
content: "Loading Analysis Method Content . . ."
},
{
key: 32,
id: "categorization_tab",
title: "Categorization",
content: "Loading Categorization Content . . ."
},
{
key: 33,
id: "custom_ngs_template",
title: "Custom NGS Template",
content: "Loading Custom NGS Template Content . . ."
}
]
};
var ConfigSettingTabContent = React.createClass({
getInitialState() {
return {
selSubTabkey:31
};
},
handleSelectSubTab(selSubTabkey) {
//alert('selected subtab' + selSubTabkey);
this.setState({selSubTabkey});
},
render() {
var Tabs = ReactBootstrap.Tabs,
Tab = ReactBootstrap.Tab;
return(
<Tabs activeKey={this.state.selSubTabkey} animation={true} tabWidth={2} paneWidth={5} position="left" onSelect={this.handleSelectSubTab}>
{
this.props.ctabs.map(function (ctab) {
return (
<Tab eventKey={ctab.key} id={ctab.id} title={ctab.title}>
{
ctab.key===31 && <ConfigEachSubTabContent subTabKey={ctab.key} id={ctab.id} title={ctab.title}/>
}
</Tab>
);
})
}
</Tabs>
);
}
});
var ConfigEachSubTabContent = React.createClass({
render() {
var subTabKey=this.props.key;
var id=this.props.id;
var title=this.props.title;
return(
<div> On Click {title} Content </div>
);
}
});
if we see
ctab.key===31 && <ConfigEachSubTabContent subTabKey={ctab.key} id={ctab.id} title={ctab.title}/>
from above code , where i am checking hardcoded ctab.key===31 instead of that i want to use it as
{this.state.selSubTabkey}===ctab.key
can you please help me to access state variables inside map?
The problem is that your map function is not bound to the outer this scope.
So three ways:
this.props.ctabs.map(function (ctab) {
return (
<Tab eventKey={ctab.key} id={ctab.id} title={ctab.title}>
{
ctab.key===this.state.selSubTabKey && <ConfigEachSubTabContent subTabKey={ctab.key} id={ctab.id} title={ctab.title}/>
}
</Tab>
);
}, this) // second parameter of map binds the scope
this.props.ctabs.map((ctab) => { // arrow function
return (
<Tab eventKey={ctab.key} id={ctab.id} title={ctab.title}>
{
ctab.key===this.state.selSubTabKey && <ConfigEachSubTabContent subTabKey={ctab.key} id={ctab.id} title={ctab.title}/>
}
</Tab>
);
})
var selTabKey = this.state.selSubTabKey; // hoisted var
this.props.ctabs.map((ctab) => {
return (
<Tab eventKey={ctab.key} id={ctab.id} title={ctab.title}>
{
ctab.key===selTabKey && <ConfigEachSubTabContent subTabKey={ctab.key} id={ctab.id} title={ctab.title}/>
}
</Tab>
);
})
Most helpful comment
The problem is that your map function is not bound to the outer
thisscope.So three ways: