0

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?

1 Answer 1

2

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> );
  }
});
Sign up to request clarification or add additional context in comments.

2 Comments

Brilliant, I tried using an expression before, but got a strange error, but this works perfectly. Thank you.

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.