Conditional Rendering with JSX

Conditional rendering in JSX lets a React component choose which UI to produce based on JavaScript conditions. Common approaches include `if` statements, ternary expressions, and `&&` for simple conditional output.

JSX is an expression-friendly syntax, so JavaScript conditional logic can determine what appears in the rendered UI. A component can use a normal `if` statement before its `return` when the logic is more involved.

For short alternatives, the ternary operator is often convenient: `condition ? <A /> : <B />`. It evaluates one of the two branches, making it useful when the UI should explicitly show either one result or another.

The logical AND operator, `&&`, is useful when something should render only when a condition is truthy. For example, `{isAdmin && <AdminPanel />}` renders the panel when `isAdmin` is truthy and otherwise produces no React element.

Be careful with values such as `0` when using `&&`. JavaScript returns the left operand when it is falsy, and React can render a numeric `0`, so `{items.length && <List />}` can unexpectedly display `0`. A comparison such as `{items.length > 0 && <List />}` avoids that problem.

Key points

Interview questions

When should conditional logic be moved outside the JSX return?

Move logic outside the JSX when it becomes difficult to read inline or requires multiple steps. A normal `if` statement can select a value or return an early branch before the component's main JSX. This keeps the markup focused on structure rather than complicated decision logic.

How would you conditionally render one of two elements in JSX?

Use a JavaScript ternary expression inside JSX when there are two possible UI branches. For example, `{isLoggedIn ? <Dashboard /> : <Login />}` selects the dashboard for a truthy condition and the login UI otherwise. This keeps a simple two-way decision close to the markup.

When would you use `&&` for conditional rendering?

Use `&&` when an element should appear only if a condition is truthy. For example, `{isAdmin && <AdminPanel />}` renders the panel for an admin and otherwise does not produce the element. It is concise when there is no alternate UI to show.

What is a common pitfall with `&&` in JSX?

The left side of `&&` follows normal JavaScript evaluation rules. If it is falsy, that value is returned rather than necessarily producing a boolean result. In particular, `0 && <List />` evaluates to `0`, and React can render that number, so an empty-list check is often clearer as `{items.length > 0 && <List />}`.