React: Conditional Rendering
So the most recent thing I have learned in React is conditional rendering, which is my favorite topic. In conditional rendering, a React component decides based on one or several conditions which DOM elements it will return. For example, based on a condition it can return whether you are logged in or not. For the condition, you can use plain javascript which includes if-else statements, ternary operators, element variables, and many more.
Let’s discuss some of the ways to implement conditional rendering in React.
1: if-else
we can apply if-else conditional logic in JSX just like we are writing code in JavaScript.
Let’s examine the following example where based on the value of isLoggedIn it will return either of the messages.
2. Ternary operator
The ternary operator is just another way to express the if-else conditional statement in JavaScript. The first part states the condition, the second part is returned when the condition is true and the last part is returned when the condition is false.
condition ? true_cond : false_cond
Let’s rewrite the above code but using the ternary operator:
3. Element variables
The element variable is an easier way to get rid of multiple return statements in your component.
In our above example, we have multiple return statements to conditionally render the part of UI.
Let’s rewrite the above example but using element variables:
By using the element variable we have made our code much cleaner easier to read.
4. Return Null
We can prevent a component from rendering by setting a null value instead of a JSX expression.
The component will be set to null if noRender is true so in this case, your component will not be rendered.
5: AND Operator (&&)
The AND operator checks for both left and right expressions are TRUE. If either of the expression returns FALSE, then the AND operator returns FALSE.
Apart from these five, there are some other ways of conditional rendering in React such as switch case, nested conditions, and HOC (Higher-Order Components).
👋 That’s all folks, thanks! if you like this post, don’t forget to leave a comment! 🤩