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
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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With