Skip to content

QuizNot attempted

Spot the bug: option shape mismatch

App builds { key, label } options but the Dropdown reads option.value. What value does onChange receive when a resource is picked?
// App.tsx
const [resourceType, setResourceType] = useState([]);
setResourceType(resources.map((r: any, i: number) => ({ key: i, label: r })));
<Dropdown options={resourceType} value={selectedValue} onChange={setSelectedValue} />
// Dropdown.tsx
interface SelectOption { value: string; label: string }
{options.map((option, index) => (
<option key={`${option.value}+${index}`} value={option.value}>{option.label}</option>
))}
1–4 to choose, Enter to submit
Show answer & explanation

Correct answer:

  • The label text: an option without a value attribute uses its text, so it works only by accident
  • React drops an attribute whose value is undefined, and an <option> with no value attribute reports its text content as its value.
  • So it works while label and id happen to be equal, and breaks the moment they differ ("Virtual Machines" vs vm, or a translated label).
  • TypeScript didn't catch it: useState([]) infers never[] and res.json() returns any, so both shapes compile.
  • Fix: one shared Option type, map to { value: r, label: r }, and type the state useState<Option[]>([]).
  • Not undefined: the DOM falls back to the text.
  • Not the index: key is React-only and never reaches the DOM.
  • Not an empty string: only the placeholder option has value="".