简体   繁体   中英

checking for first key in map with reactjs

I've got the following component in ReactJS

var MainMenu = React.createClass({
                render: function() {
                    console.log(this.props.groupsData);
                    var categories = this.props.groupsData.objects.map(function(obj){
                        return (<li><a href="#">{obj.display_name}</a></li>);   
                    });
                    return (<div className="MainMenu">
                            <ul className="nav nav-pills">{categories}</ul>

                        </div>);
                }
            });    

Now, I wish to add className='active' to the <li> element if its the first in the map. How would I achieve this?

Use JS in your expression

var MainMenu = React.createClass({
  render: function() {
    console.log(this.props.groupsData);
    var categories = this.props.groupsData.objects.map(function(obj, index) {
      // You can have a JavaScript expression in your expression 
      return ( <li className={index == 0 ? 'active' : ''}> <a href="#">{
        obj.display_name
      }</a></li> );
    });
    return ( <div className="MainMenu" >
      <ul className="nav nav-pills" >{
        categories
      }</ul>

   </div> );
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM