Skip to content
react

React Conditional Rendering

Oct 15, 2021Abhishek EH5 Min Read
React Conditional Rendering

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:

App.js
1const App = ({ list }) => {
2 if (!list) {
3 return null
4 }
5
6 return (
7 <ul>
8 {list.map(item => (
9 <li key={item.name}>{item.name}</li>
10 ))}
11 </ul>
12 )
13}
14
15export default App

You could also write this in a different way as shown below:

App.js
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 }
11
12 return null
13}
14
15export 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:

App.js
1const App = ({ list }) => {
2 if (!list) {
3 return null
4 }
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}
17
18export default App

You could also write the above example with just if statements, for better readability:

App.js
1const App = ({ list }) => {
2 if (!list) {
3 return null
4 }
5 if (list.length === 0) {
6 return <div>List is empty</div>
7 }
8
9 return (
10 <ul>
11 {list.map(item => (
12 <li key={item.name}>{item.name}</li>
13 ))}
14 </ul>
15 )
16}
17
18export default App

Conditional rendering using ternary operator

We can use ternary operator to simplify the conditional rendering as follows:

App.js
1const App = ({ isLoggedIn }) => {
2 return isLoggedIn ? <button>Logout</button> : <button>Login</button>
3}
4
5export default App

When you have multiple lines of elements to be rendered, you can wrap them inside parenthesis ():

App.js
1const App = ({ isLoggedIn }) => {
2 return isLoggedIn ? (
3 <>
4 <ShowWelcomeMessage />
5 <button>Logout</button>
6 </>
7 ) : (
8 <button>Login</button>
9 )
10}
11
12export 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:

App.js
1const App = ({ isLoading }) => {
2 return isLoading && <div>Loading...</div>
3}
4
5export default App

You can club multiple conditions together with &&

App.js
1const App = ({ isLoggedIn, balance }) => {
2 return isLoggedIn && balance === 0 && <div>Please recharge your account</div>
3}
4
5export 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:

App.js
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} />
9
10 default:
11 return null
12 }
13}
14
15export default App

If you want to embed the switch statement inside the JSX, then you can make use of immediately invoked function expressions (IIFEs).

App.js
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} />
12
13 default:
14 return null
15 }
16 })()}
17 </div>
18 )
19}
20
21export default App

Using multiple conditional rendering

You can write the above switch case example with the help of JavaScript objects as shown below:

App.js
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}
14
15export 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:

App.js
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}
16
17export 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:

App.js
1const App = ({ isLoggedIn, posts }) => {
2 return <div>{isLoggedIn ? <Posts posts={posts} /> : "Please login"}</div>
3}
4
5const Posts = ({ posts }) => {
6 return posts.length === 0 ? <AddPost /> : <ShowPosts />
7}

If you have liked article, stay in touch with me by following me on twitter.

Leave a Comment

© 2023 CodingDeft.Com