RE

JSX

React · 6 entries

JSX Syntax Rules

syntax
// Must return single root element
return (
  <div>
    <Child />
  </div>
);
// Self-closing tags required for void elements
<img src={url} alt="desc" />
example
function ProductCard({ product }) {
  return (
    <article className="product-card">
      <img src={product.imageUrl} alt={product.name} />
      <h3>{product.name}</h3>
      <p>{product.description}</p>
      <strong>${product.price.toFixed(2)}</strong>
    </article>
  );
}

Note JSX is syntactic sugar for function calls. Every tag must be closed. Use className instead of class, htmlFor instead of for. Attribute names follow camelCase convention.

Embedding Expressions

syntax
{expression}
// Any valid JavaScript expression inside curly braces
example
function PriceDisplay({ price, discount }) {
  const finalPrice = price * (1 - discount);
  const savings = price - finalPrice;

  return (
    <div>
      <p>Original: ${price.toFixed(2)}</p>
      <p>You save: ${savings.toFixed(2)}</p>
      <p className="total">Total: ${finalPrice.toFixed(2)}</p>
      <small>Applied {(discount * 100).toFixed(0)}% off</small>
    </div>
  );
}

Note You can embed any JavaScript expression inside curly braces: variables, function calls, math, ternaries. Statements (if, for, while) cannot appear inside JSX directly -- use them before the return.

Conditional Rendering Patterns

syntax
// AND pattern
{isLoggedIn && <Dashboard />}
// Ternary
{isLoggedIn ? <Dashboard /> : <LoginForm />}
// IIFE for complex logic
{(() => { if (x) return <A />; return <B />; })()}
example
function StatusBadge({ status }) {
  return (
    <span>
      {status === "active" && <span className="dot green" />}
      {status === "inactive" ? (
        <span className="label">Away</span>
      ) : (
        <span className="label">{status}</span>
      )}
    </span>
  );
}

Note For more than two branches, extract the logic into a variable or helper function above the return statement rather than nesting ternaries. Readable code wins over clever one-liners.

Spread Attributes

syntax
<Component {...propsObject} />
example
function FormField({ label, ...inputProps }) {
  return (
    <div className="field">
      <label>{label}</label>
      <input {...inputProps} />
    </div>
  );
}

// Usage: all standard input attributes are forwarded
<FormField
  label="Email"
  type="email"
  placeholder="you@example.com"
  required
/>

Note Spread is great for forwarding props. Be careful: it can pass unintended attributes to DOM elements. Destructure known props first, then spread the rest.

JSX vs createElement

syntax
// JSX (compiled to createElement)
<Button color="blue">Save</Button>

// Equivalent createElement call
React.createElement(Button, { color: "blue" }, "Save")
example
// This JSX:
const element = (
  <div className="container">
    <h1>Title</h1>
    <p>Paragraph</p>
  </div>
);

// Compiles to:
const element = React.createElement(
  "div",
  { className: "container" },
  React.createElement("h1", null, "Title"),
  React.createElement("p", null, "Paragraph")
);

Note You almost never need to call createElement directly. JSX is syntactically cleaner and the standard in the ecosystem. The JSX transform in modern setups does not require importing React at the top of every file.

Inline Style Objects

syntax
<div style={{ property: value }} />
example
function ProgressBar({ percent }) {
  return (
    <div
      style={{
        width: `${percent}%`,
        height: "8px",
        backgroundColor: percent > 70 ? "#4caf50" : "#ff9800",
        borderRadius: "4px",
        transition: "width 0.3s ease",
      }}
    />
  );
}

Note Style properties use camelCase (backgroundColor, not background-color). Values that need units must include them as strings ("8px"), except for unitless properties like opacity and zIndex which accept numbers.