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
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:
This is saying, if the variable
<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:
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:
Expressions in the ternary operator or the right hand side expression of the logical && operator can be wrapped in parantheses for better readability:
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 👇