25. Conditional Rendering
Displaying UI Based on Logic
Your applications will rarely look the same at all times. If a user is logged in, you show a Dashboard. If they aren't, you show a Login button. If data is fetching, you show a spinner. Conditional Rendering is how React decides what JSX to display based on the current state.
Method 1: Early Returns (if/else)
Because React components are just JavaScript functions, you can use standard if statements to return completely different UI before the rest of the component executes.
Method 2: Ternary Operator (? :)
If you want to conditionally render elements inside a block of JSX, you cannot use an if statement (because JSX requires expressions). Instead, use the JavaScript ternary operator.
Method 3: Logical AND (&&)
Sometimes you only want to render something if a condition is true, and render nothing if it is false. The && operator is perfect for this.
Warning: Be careful with the number 0. In JavaScript, 0 is falsy. If you write {messages.length && <p>New messages!</p>}, and the length is 0, React will literally render a "0" on the screen. Always use strict booleans: {messages.length > 0 && ...}.
Knowledge Check
Ready to test your understanding of 25. Conditional Rendering?