Add a notifications opt-in to the profile form

React · React · intermediate · modification

Refactors the profile form into a schema-driven renderer: a `PROFILE_SCHEMA` describing each field and a `FIELD_COMPONENTS` registry mapping a field `type` to its control, so new fields drop in by adding a schema entry with no JSX changes. Adds the notifications checkbox as the third schema entry.

`initial` is the current profile ({ displayName, email, notifications }) and `onSave` persists the edited values. The form is small and static.

Requirements

Files touched

--- src/components/ProfileForm.jsx
 import { useState } from 'react';
+
+const FIELD_COMPONENTS = {
+  text: ({ value, onChange }) => (
+    <input type="text" value={value} onChange={(e) => onChange(e.target.value)} />
+  ),
+  email: ({ value, onChange }) => (
+    <input type="email" value={value} onChange={(e) => onChange(e.target.value)} />
+  ),
+  checkbox: ({ value, onChange }) => (
+    <input type="checkbox" checked={value} onChange={(e) => onChange(e.target.checked)} />
+  ),
+};
+
+const PROFILE_SCHEMA = [
+  { name: 'displayName', label: 'Display name', type: 'text' },
+  { name: 'email', label: 'Email', type: 'email' },
+  { name: 'notifications', label: 'Email me product updates', type: 'checkbox' },
+];
+
+function DynamicField({ field, value, onChange }) {
+  const Control = FIELD_COMPONENTS[field.type];
+  return (
+    <label>
+      {field.label}
+      <Control value={value} onChange={onChange} />
+    </label>
+  );
+}

Review this PR

React practice