Accessing deeper array keys

- 1 answer

Ad

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.

Ad

Answer

Ad

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).

Ad
source: stackoverflow.com
Ad