Props

The Die component works, but it always shows the same value because the value is hardcoded. In this section, you will make it configurable using props. Props are how React passes data from a parent component to a child.

Making the Die Configurable

Props (short for “properties”) work like HTML attributes. When you write <Die value={3} />, you are passing the number 3 as the value prop. The component receives it as a parameter and can use it to decide what to render.

Update src/components/Die.tsx:

const dotPositions: Record<number, number[]> = {
  1: [4],
  2: [2, 6],
  3: [2, 4, 6],
  4: [0, 2, 6, 8],
  5: [0, 2, 4, 6, 8],
  6: [0, 2, 3, 5, 6, 8],
};

// 👀 Define the prop types
interface DieProps {
  value: number;
}

function Die({ value }: DieProps) { // 👀 Accept value as a prop
  const dots = dotPositions[value] ?? [];

  return (
    <button
      className="grid grid-cols-3 grid-rows-3 gap-2 rounded-xl bg-white p-4 shadow-lg"
      style={{ width: "120px", height: "120px" }}
    >
      {Array.from({ length: 9 }).map((_, i) => (
        <div key={i} className="flex items-center justify-center">
          {dots.includes(i) && (
            <div className="h-5 w-5 rounded-full bg-gray-800" />
          )}
        </div>
      ))}
    </button>
  );
}

export default Die;

The key changes:

  • interface DieProps defines the shape of the props this component expects. TypeScript enforces that any parent using <Die> must pass a value number.
  • { value }: DieProps uses destructuring to extract the value directly from the props object. The hardcoded const value = 5 is gone. The value now comes from the parent.

Now update App.tsx to pass a value:

import Die from "./components/Die";

function App() {
  return (
    <div className="flex min-h-screen flex-col items-center justify-center gap-8 bg-green-700">
      <h1 className="text-4xl font-bold text-white">Dice Roller</h1>
      <Die value={3} /> {/* 👀 Pass value as a prop */}
    </div>
  );
}

export default App;

Try changing the value to different numbers (1–6) and watch the die face update. The same component shows a different face depending on the value it is given.

Checkpoint: Commit your progress.

git add .
git commit -m "dice-04: Make Die configurable with props"
git push