Accessing deeper array keys
I am trying to create a navigation menu which supports dropdown items. I have created
var menuItems={
items:[
{
title:"Home",
id:1
},
{
title:"Download App",
children:["iOS","Android","Windows"],
id:2
},
{
title:"About",
id:3
}
]
};
This is my Menu Prototype Class:
var MenuProto = React.createClass({
render: function(){
return <li><a>{this.props.title}</a>
<ul className="dropdown-menu">
<li><a>{this.props.children}</a></li>
</ul>
</li>
}
});
And this is where it is called:
var Menu = React.createClass({
render : function(){
var fullmenu = this.props.items.map(function(item){
return <MenuProto {...item}/>
});
return <ul className="nav navbar-nav navbar-right">
{fullmenu}
</ul>
}
});
Apparently this.props.children gets all the array and uses renders it on the menu while I need it to get them one by one. I have tried creating a var similar to fullmenu which would iterate through childrens of this.props.children one by one but I can't figure out how.
I would also need a hint on how to make a conditional to see if an object has or doesnt have the children key.
Any help would be greatly appreciated.
Answer
You can iterate on this.props.children
using the React.Children
utilities:
var MenuProto = React.createClass({
render: function(){
return <li><a>{this.props.title}</a>
<ul className="dropdown-menu">
{React.Children.map(this.props.children, function(child) {
return <li key={child.id}><a>{child.title}</a></li>
})}
</ul>
</li>
}
});
Since you want to support nested items, you'll need some additional custom logic.
You can check to see if an object has a children
key by simply testing for the existence of whatever.children
; if it doesn't have that key, it will be a falsy value (specifically undefined
).
Related Questions
- → Import statement and Babel
- → should I choose reactjs+f7 or f7+vue.js?
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → .tsx webpack compile fails: Unexpected token <
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → React Native with visual studio 2015 IDE
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
- → How do I determine if a new ReactJS session and/or Browser session has started?
- → Alt @decorators in React-Native
- → How to dynamically add class to parent div of focused input field?