0

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.

Alan Jenshen
  • 3,159
  • 9
  • 22
  • 35

3 Answers3

0

To put the condition inside JSX, we can use the ternary operator, like this:

{1==1 ? <div> hello </div> : null}

Return null if you don't want to render anything when condition fails.

Use this:

<li key={i} onClick={e => dropdownHandler(obj.handlerName)}>
      {obj.visible ? 
           <a>
              {obj.iconClasses && 
                   <i className={obj.iconClasses}></i>
              }
              {obj.name}
           </a>
       : null}
       {obj.visible ? 
           <div key={i} className={classnames({'divider':obj.divider})}></div>
       : null}
</li>
Mayank Shukla
  • 100,735
  • 18
  • 158
  • 142
0

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.

Community
  • 1
  • 1
madox2
  • 49,493
  • 17
  • 99
  • 99
0

One of the shortcomings of React is that you need to wrap every block in a single container. They are working on the solution, but it might take a while. In the meantime, the simplest way to skip the extra <div in your case is to do the check for both elements under it separately:

{obj.visible &&
  <a>
    {obj.iconClasses && 
      <i className={obj.iconClasses}></i>
    }
    {obj.name}
  </a>
{obj.visible && <div key={i} className={classnames({'divider':obj.divider})}></div>}
Waiski
  • 9,214
  • 3
  • 21
  • 30