TutorialsReactJSX Deep Dive
Share:

JSX Deep Dive

beginner

Part of React Fundamentals

Theory

JSX is a syntax extension that combines JavaScript and HTML-like markup. It gets transpiled to React.createElement() calls by tools like Babel.

Syntax Rules

  • JSX must have a single root element (use <Fragment> or <>...</>)
  • Self-closing tags: <img />, <input />
  • Use className instead of class, htmlFor instead of for
  • Attributes are camelCase: onClick, onChange

Expressions

Embed any JavaScript expression with single curly braces {}. This includes variables, function calls, ternary operators, and array methods. Statements (if, for, switch) are not allowed directly in JSX.

Conditional Rendering

Use ternary operators, logical AND (&&), or IIFEs to conditionally render elements:

{isLoggedIn ? <Dashboard /> : <Login />}
{showWarning && <Warning />}

Lists and Keys

When rendering arrays with map(), each element needs a unique key prop. Keys help React identify which items changed, were added, or removed.

Practical Examples

Example 1: Conditional Rendering and Lists
jsx
Example 2: Fragments and Expressions
jsx

Exercises

Render a Filtered List

easy

Create a component that has an array of product objects (name, price, inStock). Render only the products that are in stock using filter() and map(). Use keys and conditional rendering.

Expected Output:

A list showing only Laptop and Tablet

Mini Quiz

Mini Quiz