Alan Jenshen Alan Jenshen - 6 months ago 22
Javascript Question

Skip jsx's div wrapping in map

I have an array object that used this component to display a UI. I have a problem, my style broke because of an extra .

<ul className="dropdown-menu">
{map(listItems, (obj,i) =>
<li key={i} onClick={e => dropdownHandler(obj.handlerName)}>
{obj.visible && <div>
<a>
{obj.iconClasses &&
<i className={obj.iconClasses}></i>
}
{obj.name}
</a>
<div key={i} className={classnames({'divider':obj.divider})}></div>
</div>
}
</li>
)}
</ul>


In the line of
{obj.visible ..
what else can I do? I do not want to include a
div
.

Answer Source

You can simply use two conditionals and omit the wrapping element:

<li key={i} onClick={e => dropdownHandler(obj.handlerName)}>
  {obj.visible &&
    <a>
      {obj.iconClasses && 
        <i className={obj.iconClasses}></i>
      }
      {obj.name}
    </a>
  }
  {obj.visible &&
    <div key={i} className={classnames({'divider':obj.divider})}></div>
  }
</li>

Furthermore using array indexes as keys is an anti-pattern. You should use some business keys instead. More info in this answer.