JSX & Conditional Rendering
Definition
JSX is a syntax extension for JavaScript that looks similar to XML/HTML. Conditional rendering in React works the same way conditions work in JavaScript using if statements, ternary operators, or logical && operators to render different UI based on state.
Explain Like I'm New
JSX lets us write HTML directly inside our JavaScript! It makes building UIs incredibly visual. Since it's still JavaScript under the hood, we can inject logic right into the HTML. If we want to show a 'Login' button when a user is signed out, and a 'Profile' button when they are signed in, we just use a simple JS 'if/else' condition right inside the UI code.
Real World Example
When fetching data, you show a `<Spinner />` if `isLoading === true`. Once the data arrives, the condition changes, and you render the `<DataList />` instead.
Common Use Cases
- •Writing declarative UI components
- •Toggling UI elements (modals, dropdowns) based on state
- •Rendering lists of data using `.map()` inside JSX
Interactive Example
import React, { useState } from 'react'; export default function UserStatus() { const [isLoggedIn, setIsLoggedIn] = useState(false); const messages = ['Update 1', 'Update 2']; return ( <> {/* 1. Ternary Operator (If / Else) */} {isLoggedIn ? ( <h1>Welcome back, User!</h1> ) : ( <h1>Please sign in.</h1> )} {/* 2. Logical && Operator (If True, Do This) */} {/* Danger: Don't do `messages.length &&`, always use boolean comparisons */} {isLoggedIn && messages.length > 0 && ( <p>You have {messages.length} unread messages.</p> )} {/* A simple JSX button with an event listener */} <button onClick={() => setIsLoggedIn(!isLoggedIn)}> Toggle Login State </button> </> ); }
Interview Questions
basic
- What is JSX?
- Why do you need to use `className` instead of `class` in JSX?
intermediate
- What is the difference between `&&` and the ternary operator `? :` for conditional rendering?
- Why must React components return a single parent element (or Fragment)?
advanced
- How does Babel transform JSX under the hood?
- Can you use an `if` statement directly inside a JSX expression block `{}`?
trick
- If you conditionally render `0 && <Component />`, what does React actually render to the screen?