React Fundamentals

0% completed

Previous
Next
Conditional Rendering with Multiple Returns

There is an option of conditional rendering using multiple returns to handle different conditions, returning early for each case.

When using multiple returns, you can handle different conditions separately, reducing the need for deeply nested conditions and improving the overall structure of your code.

This approach simplifies the logic and improves the readability of your components.

Example

Let’s look at a simple example of a component that shows different messages based on whether a user is logged in or not.

function WelcomeMessage() { const isLoggedIn = true if (!isLoggedIn) { return <h1>Please log in to continue.</h1>; } return <h1>Welcome back, User!</h1>; }

In this WelcomeMessage component:

  • The first return checks if the user is not logged in. If isLoggedIn is false, it immediately returns the "Please log in to continue." message.
  • If the user is logged in, the second return is triggered, rendering the "Welcome back, User!" message.

By using multiple return statements, the logic becomes more straightforward, and the component doesn't get cluttered with conditional operators or deeply nested if-else statements.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next