JSX & Rendering
EasyJSX is a syntax extension that lets you write HTML-like markup inside JavaScript. A compiler transforms each JSX element into React.createElement() calls that produce plain objects describing the UI tree. Understanding JSX is essential because every React component returns JSX.
Interactive Visualization
Key Points
- JSX compiles to React.createElement() or the jsx() runtime function
- Curly braces {} embed JavaScript expressions inside JSX
- JSX expressions must return a single root element or Fragment
- Attributes use camelCase: className, htmlFor, onClick
- JSX prevents injection attacks by escaping embedded values
- Components must start with an uppercase letter to distinguish from HTML tags
Code Examples
JSX Compilation
// JSX syntax const element = <h1 className="title">Hello</h1> // Compiles to (classic runtime) const element = React.createElement( 'h1', { className: 'title' }, 'Hello' ) // React 17+ automatic runtime import { jsx } from 'react/jsx-runtime' const element = jsx('h1', { className: 'title', children: 'Hello' })
JSX is syntactic sugar that compilers like Babel or SWC transform into function calls producing plain objects
Embedding Expressions
interface UserProps { name: string age: number isAdmin: boolean } function UserCard({ name, age, isAdmin }: UserProps) { return ( <div> <h2>{name}</h2> <p>Born around {new Date().getFullYear() - age}</p> {isAdmin ? <span>Admin</span> : <span>User</span>} {age >= 18 && <p>Eligible to vote</p>} </div> ) }
Curly braces accept any JavaScript expression including variables, function calls, and ternaries for conditional rendering
Fragments
import { Fragment } from 'react' function Greeting() { return ( <> <h1>Hello</h1> <p>Welcome back</p> </> ) } // Explicit Fragment with key for lists function Glossary({ items }: { items: Item[] }) { return ( <dl> {items.map((item) => ( <Fragment key={item.id}> <dt>{item.term}</dt> <dd>{item.definition}</dd> </Fragment> ))} </dl> ) }
Fragments group elements without adding extra DOM nodes, and the explicit syntax supports the key prop for lists
Common Mistakes
- Using class instead of className for CSS classes
- Forgetting that JSX expressions must have a single root element
- Using if statements inside JSX instead of ternary expressions or && operator
Interview Tips
- Explain that JSX is not HTML but compiles to JavaScript function calls
- Know the difference between the classic and automatic JSX transform
- Be ready to explain why React uses className instead of class