SkillPilotAI

Events and conditional rendering

Events let the UI react to the user (clicks, typing, submits), and conditional rendering decides which UI to show for the current state. Together they cover two classic bugs: calling a handler during render (infinite loop) and the stray 0 rendered by &&.

28.1 Event handlers

  • Define a function (handleClick) and pass it to a camelCase prop: onClick, not onclick.
  • Pass the function itself; React calls it when the click happens.
  • Naming convention: handlers start with handle (handleClick, handleSubmit); props that receive them start with on (onClick, onRemove).
React (JSX)
function BuyButton() {  function handleClick() {    console.log("Added to cart");  }   return (    <button onClick={handleClick}>      Add to cart    </button>  );}
Output
-- after click --[button] Add to cartConsole: Added to cart

28.2 The problem: passing an argument

  • A size picker with S and L buttons; size state starts at "M".
  • onClick={setSize("S")} looks right because we want to pass an argument.
  • The page opens blank with Error: Too many re-renders.
React (JSX)
import { useState } from "react"; function SizePicker() {  const [size, setSize] = useState("M");   return (    <div>      <p>Size: {size}</p>      <button onClick={setSize("S")}>S</button>      <button onClick={setSize("L")}>L</button>    </div>  );}
Output
Screen: page blankError: Too many re-renders.

28.3 Why the screen went blank

  • The brackets call setSize during render, not on click.
  • Updating state during render triggers another render, which calls setSize again: an infinite loop.
  • React stops the loop and throws. onClick needs a function, not the result of calling one.
Calling a handler during render
  1. 1.Render runs: onClick={setSize("S")} calls setSize immediately

  2. 2.State update: React schedules another render

  3. 3.Render again: setSize is called again

  4. 4.Infinite loop: React throws Too many re-renders

Fix: onClick={() => setSize("S")}

28.4 Fix: an arrow function

  • onClick={() => setSize("L")} only creates the arrow function during render.
  • On click React runs it, which calls setSize("L").
  • Use this pattern whenever a handler needs an argument.
React (JSX)
import { useState } from "react"; function SizePicker() {  const [size, setSize] = useState("M");   return (    <div>      <p>Size: {size}</p>      <button onClick={() => setSize("S")}>S</button>      <button onClick={() => setSize("L")}>L</button>    </div>  );}
Output
-- start --Size: M[button] S[button] L-- after clicking L --Size: L[button] S[button] L
You writeWhat onClick receivesResult
onClick={handleClick}A function referenceRuns on click
onClick={handleClick()}The return value (called during render)Runs on every render; with setState, infinite loop
onClick={() => setSize("L")}A new arrow functionRuns on click with the argument

28.5 Conditional rendering: ternary

  • You cannot write if inside JSX, so use the ternary operator: condition ? A : B.
  • inStock true shows the Add to cart button; false shows Out of stock in the same place.
React (JSX)
function Product({ inStock, offer }) {  return (    <div>      <h3>Pixel 9</h3>      {inStock ? (        <button>Add to cart</button>      ) : (        <p>Out of stock</p>      )}      {offer && <p>Offer: {offer}</p>}    </div>  );}
Output
-- inStock true --# Pixel 9[button] Add to cart-- inStock false --# Pixel 9Out of stock

28.6 Conditional rendering: &&

  • {offer && <p>Offer: {offer}</p>}: if the left side is truthy the right side renders, otherwise nothing.
  • Rule: ternary to pick one of two UIs, && to only show or hide.
Output
-- offer null --# Pixel 9[button] Add to cart-- offer "10% off" --# Pixel 9[button] Add to cartOffer: 10% off
Which conditional to use
  1. 1.Need one of two UIs? Use a ternary: cond ? <A /> : <B />

  2. 2.Only show or hide? Use &&, with a boolean on the left

  3. 3.Big or multi-branch logic? Use if before return / early return

  4. 4.Render nothing? Return null

28.7 The 0 gotcha

Checkpoint: with count = 0, {count && ...} renders 0. 0 is falsy, so && returns the left value; React ignores false and null but renders the number 0 as text.

React (JSX)
function CartBadge({ count }) {  return (    <div>      {count && <span>{count} items</span>}    </div>  );}
Output
0
  • Very common with cart counts and list.length checks.
  • Fix: make the left side a real boolean (count > 0) or use a ternary that returns null.
React (JSX)
// Right: boolean on the left, count 0 shows nothingfunction CartBadge({ count }) {  return (    <div>      {count > 0 && <span>{count} items</span>}    </div>  );}
Value on the left of &&Rendered?
false, null, undefinedNothing
0The text 0
NaNThe text NaN
"" (empty string)Nothing visible
count > 0 (boolean)Nothing when false

28.8 Common mistakes

  • onClick={fn()} instead of onClick={fn} or an arrow function.
  • A number on the left of && (count && ...) rendering 0.
  • Writing if/else inside JSX braces: only expressions work there. For big logic, write the if before return (e.g. early return "No orders yet" when orders are empty).

28.9 Best practices

  1. onClick gets a function, not a call; use an arrow function for arguments.
  2. Naming: handleX for handlers, onX for props.
  3. Keep a boolean on the left of &&.
  4. Use an early return or a separate variable for complex conditions.

28.10 Interview tips

  • Conditional rendering: if and early return outside JSX; ternary or && inside JSX.
  • Mention the 0 gotcha: a number on the left of && renders 0, so use a boolean condition.
  • onClick takes a function reference; calling the function would run it during render.
  • Use an arrow function to pass arguments to a handler.
  • Return null from a component to render nothing.