0

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.

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, that's exactly what I needed. Anyway upon reading the documentation for React.Children it came to my attention the function fn (child) { where when invoking fn it is said that if the children is null or undefined it returns null or undefined, and as such saving me a lot of hassle!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.