Inline Conditional Rendering JSX in React
When returning JSX from a React component you may wish to return output depending on the condition of the value of some variable.
An obvious example is a component loading state, which could be displayed dependent on a state variable called isLoading
. If isLoading
is true
then we return a loading UI, but if it's false
we show the component.
To handle the if/else conditional inline in JSX we can use a ternary operator:
return (
<>
{isLoading
? <p>Loading...</p>
: <div>(Your Component Here)</div>
}
</>
)
This is saying, if the variable isLoading
is true
, output <p>Loading...</p>
, else output the <div>
. (Don't forget to make sure this is wrapped in an enclosing DOM element or the React.Fragment (<></>
))
But what if you just want an if, and no else? Perhaps you have another boolean for if there is an error. If the error if true, show a warning box, otherwise do nothing.
You could write this in the same vein, with an empty string for the else expression:
return (
<>
{isError
? <p>Error! {errorMessage}</p>
: ``
}
</>
)
But, seems like we don't really need that else. Instead, you can make use of JavaScript's logical && operater which returns the expression on the right of the operator if both expressions coerce to true.
return (
<>
{isError && <div>Error! {errorMessage} </div>}
</>
)
The errorMessage
is a variable that would have been set by state or received as props to the component.
You can also return an array of items inline in the JSX:
return (
<ul>
{data && data.length
?
data.map(item => <li key={item.id}>{item.title}</li>)
:
<p>No Data</p>
}
</ul>
)
Expressions in the ternary operator or the right hand side expression of the logical && operator can be wrapped in parantheses for better readability:
return (
<>
{isLoading
? 'Loading...'
: (
<div>
<h1>My Component Title</h1>
<h2>Subheading</h2>
</div>
)}
<div>Some more output, not relevant to the conditional.</div>
</>
)
If you have any questions or comments or want to connect, you can follow me on Twitter, or sign up to the newsletter in the footer for front-end articles to your inbox 👇