React by Patrik

React Conditional Rendering

In React, you can conditionally render components.

There are several ways to achieve conditional rendering:

  1. If statement: Use a regular if statement to conditionally render components or elements based on a condition.

  2. Ternary operator: Use a ternary operator (condition ? trueBlock : falseBlock) to render different components or elements based on a condition.

  3. Logical && operator (Short Circuit Evaluation): Use the logical && operator (condition && renderBlock) to conditionally render a block of JSX based on a condition. The block is only rendered if the condition is true.

  4. Switch statement: Use a switch statement to handle multiple conditions and render different components or elements based on each condition.

  5. Inline condition: Use inline conditions within JSX ({condition ? renderBlock : null}) to render a block of JSX based on a condition.

  6. Render function: Use a render function or a component that returns JSX. Inside the function, you can implement any JavaScript logic to conditionally render components or elements.

...see more

The conditional (ternary) operator is the only JavaScript operator that takes three operands. This operator is frequently used as a shortcut for the if statement.

Syntax: {cond ? <A /> : <B />} means “if cond, render <A />, otherwise <B />.

Sample

{itemCollapsed ? (
   <CommandItem title='Expand' />
 ) : (
   <CommandItem title='Collapse' />
 )}
...see more

In React it often comes up when you want to render some JSX when the condition is true, or render nothing otherwise. 

Syntax: {cond && <A />} means “if cond, render <A />, otherwise nothing”.

Sample

{article.content.length > 0 && (
   <ArticleContent content={article.content} slug={article.slug} />
)

Comments