SyntaxStudy
Sign Up
React Conditional Rendering with Ternary and &&
React Beginner 1 min read

Conditional Rendering with Ternary and &&

Conditional rendering in React is achieved with ordinary JavaScript logic embedded in JSX. The two most common patterns are the ternary operator and the short-circuit `&&` operator. The ternary `condition ? : ` renders one of two elements. The short-circuit `condition && ` renders the element only when the condition is truthy and renders nothing when it is falsy — because React ignores `false`, `null`, and `undefined`. A subtle gotcha with `&&` occurs when the left-hand side evaluates to a falsy non-boolean such as `0` or `""`. React does not render `false`, but it does render `0` as the text "0". Always use a proper boolean comparison (`count > 0 && ` instead of `count && `) to avoid accidental numeric output. For more than two branches, nesting ternaries becomes hard to read. Alternatives include an `if`/`else if` block before the return statement, a helper function that returns JSX, or an object lookup keyed by a status string. Moving conditional logic above the JSX keeps the return statement clean and the branching explicit. React does not have a dedicated template directive for conditionals — it relies entirely on JavaScript, which is both its greatest flexibility and a source of subtle bugs if you are not careful.