Table of Contents
There are several ways to do conditional rendering in React based on the situation. In this article, we will see few practical approaches in conditional rendering components in React.
Conditional rendering using If statement
Say you have a list of items and you want to show the list only when it exists, then you can render it as follows:
1const App = ({ list }) => {2 if (!list) {3 return null4 }56 return (7 <ul>8 {list.map(item => (9 <li key={item.name}>{item.name}</li>10 ))}11 </ul>12 )13}1415export default App
You could also write this in a different way as shown below:
1const App = ({ list }) => {2 if (list) {3 return (4 <ul>5 {list.map(item => (6 <li key={item.name}>{item.name}</li>7 ))}8 </ul>9 )10 }1112 return null13}1415export default App
Conditional rendering using if-else statement
In the above example, if we want to display a message to the user when the list is empty, we can achieve it with an if-else statement:
1const App = ({ list }) => {2 if (!list) {3 return null4 }5 if (list.length === 0) {6 return <div>List is empty</div>7 } else {8 return (9 <ul>10 {list.map(item => (11 <li key={item.name}>{item.name}</li>12 ))}13 </ul>14 )15 }16}1718export default App
You could also write the above example with just if statements, for better readability:
1const App = ({ list }) => {2 if (!list) {3 return null4 }5 if (list.length === 0) {6 return <div>List is empty</div>7 }89 return (10 <ul>11 {list.map(item => (12 <li key={item.name}>{item.name}</li>13 ))}14 </ul>15 )16}1718export default App
Conditional rendering using ternary operator
We can use ternary operator to simplify the conditional rendering as follows:
1const App = ({ isLoggedIn }) => {2 return isLoggedIn ? <button>Logout</button> : <button>Login</button>3}45export default App
When you have multiple lines of elements to be rendered, you can wrap them inside parenthesis ():
1const App = ({ isLoggedIn }) => {2 return isLoggedIn ? (3 <>4 <ShowWelcomeMessage />5 <button>Logout</button>6 </>7 ) : (8 <button>Login</button>9 )10}1112export default App
Conditional rendering using Short Circuit && operator
When you want to display something when a certain condition satisfied and don't want to render anything when the condition fails, && operator is your best friend:
1const App = ({ isLoading }) => {2 return isLoading && <div>Loading...</div>3}45export default App
You can club multiple conditions together with &&
1const App = ({ isLoggedIn, balance }) => {2 return isLoggedIn && balance === 0 && <div>Please recharge your account</div>3}45export default App
Conditional rendering using a switch statement
When you have more than two outputs for an expression, then instead of going for if-else ladder, we can use switch statement:
1const App = ({ status, message }) => {2 switch (status) {3 case "info":4 return <Info message={message} />5 case "warning":6 return <Warning message={message} />7 case "error":8 return <Error message={message} />910 default:11 return null12 }13}1415export default App
If you want to embed the switch statement inside the JSX, then you can make use of immediately invoked function expressions (IIFEs).
1const App = ({ status, message }) => {2 return (3 <div>4 {(() => {5 switch (status) {6 case "info":7 return <Info message={message} />8 case "warning":9 return <Warning message={message} />10 case "error":11 return <Error message={message} />1213 default:14 return null15 }16 })()}17 </div>18 )19}2021export default App
Using multiple conditional rendering
You can write the above switch case example with the help of JavaScript objects as shown below:
1const App = ({ status, message }) => {2 return (3 <div>4 {5 {6 info: <Info message={message} />,7 warning: <Warning message={message} />,8 error: <Error message={message} />,9 }[status]10 }11 </div>12 )13}1415export default App
Here status can have any of the 3 values: info, warning, and error. Based on the status value, the corresponding component will be rendered.
Nested conditional rendering
You can use ternary operators to nest multiple conditions:
1const App = ({ isLoggedIn, posts }) => {2 return (3 <div>4 {isLoggedIn ? (5 posts.length === 0 ? (6 <AddPost />7 ) : (8 <ShowPosts />9 )10 ) : (11 "Please login"12 )}13 </div>14 )15}1617export default App
Here we check if the user is logged in, if yes then we check if the user has any posts. If they do not have any posts then we ask them to add one and if there are posts then we show the posts. If the user is not logged in, then we ask them to log in.
This type of nesting is not recommended since it hinders readability. When you have nested conditions, always split them into multiple components:
1const App = ({ isLoggedIn, posts }) => {2 return <div>{isLoggedIn ? <Posts posts={posts} /> : "Please login"}</div>3}45const Posts = ({ posts }) => {6 return posts.length === 0 ? <AddPost /> : <ShowPosts />7}
Do follow me on twitter where I post developer insights more often!
Leave a Comment