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
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?