Skip to main content

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.