Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I render multiple element in a ternary condition without else?

I have the following code that allows me to retrieve a user's personal link on several social networks:

<ul className="navbar-nav my-2 my-lg-0">
  {
    settings !== null &&
      <li className="nav-item">
        <a className="nav-link" href={settings.facebook.url}>Facebook</a>
      </li>
  }
  {
    settings !== null &&
      <li className="nav-item">
        <a className="nav-link" href={settings.twitter.url}>Articles</a>
      </li>
  }
</ul>

However, since the settings object is retrieved by an Ajax call to the database, this is asynchronous and I have to make sure that `settings exists before making it showing up some datas.

My question is, since the following doesn't work:

<ul className="navbar-nav my-2 my-lg-0">
  {
    settings !== null &&
      <li className="nav-item">
        <a className="nav-link" href={settings.facebook.url}>Facebook</a>
      </li>

      <li className="nav-item">
        <a className="nav-link" href={settings.twitter.url}>Articles</a>
      </li>
  }
</ul>

Is there any way to make one verification for multiple React elements?

Thank you in advance

like image 564
Jaeger Avatar asked Dec 01 '22 10:12

Jaeger


2 Answers

you can use an array to return multiple elements

<ul className="navbar-nav my-2 my-lg-0">
  {
    settings !== null ?
      [
         <li className="nav-item">
           <a className="nav-link" href={settings.facebook.url}>Facebook</a>
         </li>,
         <li className="nav-item">
           <a className="nav-link" href={settings.twitter.url}>Articles</a>
         </li>
      ]
      :
      null
  }
</ul>
like image 188
John Avatar answered Mar 06 '23 04:03

John


The elements returned if the condition passes need to be wrapped inside a single element, such as <div> or, as @kunukn suggests <React.Fragment>

<ul>
  {
    setting !== null && (
      <React.Fragment>
        <li className="nav-item">
          <a className="nav-link" href={settings.facebook.url}>Facebook</a>
        </li>
        <li className="nav-item">
          <a className="nav-link" href={settings.twitter.url}>Articles</a>
        </li>
      </React.Fragment>
    )
  }
</ul>
like image 33
sketchedin Avatar answered Mar 06 '23 05:03

sketchedin