Dynamic Forms
Difficulty: Advanced
Problem Statementβ
Render dynamic list of forms; clicking "Add More" appends another form block.
Live Demoβ
Try the running app below β this is the target behavior for the challenge.
Dynamic Forms β Live Demo
What Interviewers Expectβ
- Dynamic array of form entities in state.
- Stable keys per form instance.
- Each form keeps its own input state.
Step-by-Step Implementationβ
Step 1 β forms array stateβ
Store { id, name } objects.
const [forms, setForms] = useState([{ id: 1, name: '' }]);
Step 2 β Add form actionβ
Append new form with unique id.
setForms((prev) => [...prev, { id: prev.length + 1, name: '' }]);
Step 3 β Update one formβ
Map and update only matching id.
prev.map((f) => (f.id === id ? { ...f, name } : f))
Complete Implementationβ
Copy-paste ready single-file solution. Use this as your reference after attempting the challenge yourself, or paste it into CodeSandbox / StackBlitz to run locally.
App.jsx
import React, {useState} from 'react';
export default function App() {
const [forms, setForms] = useState([{id: 1, name: ''}]);
const addForm = () => {
setForms((prev) => [...prev, {id: prev.length + 1, name: ''}]);
};
const updateForm = (id, name) => {
setForms((prev) => prev.map((form) => (form.id === id ? {...form, name} : form)));
};
return (
<div>
{forms.map((form) => (
<div key={form.id} style={{marginBottom: '1rem'}}>
<input
placeholder={`Name (${form.id})`}
value={form.name}
onChange={(e) => updateForm(form.id, e.target.value)}
/>
</div>
))}
<button type="button" onClick={addForm}>
Add More
</button>
</div>
);
}
Final Checklistβ
- UI works for primary flow
- Edge cases handled (empty/disabled/loading where relevant)
- State updates are immutable
- Components are readable and reasonably split
- You can explain trade-offs out loud in an interview
Next Challengeβ
Continue to the next item in the sidebar when you're comfortable implementing this from scratch in 30β45 minutes.