Course contentsShow
← React
Lesson 1206 of 2,39631. Forms in ReactFree lesson

Arrays in Form State

Managing dynamic field lists where users can add/remove items like addresses, phone numbers, or line items.

Arrays in Form State

You'll learn: How to manage dynamic lists of form fields in React state so users can add, remove, and edit multiple similar items like addresses or line items.

The Dynamic List Problem

Many real-world forms need repeatable sections. Think of an invoice form where users add multiple line items, or a profile form where someone can list several phone numbers. These aren't single values—they're arrays in your form state that grow and shrink based on user actions.

Core Pattern: Array of Objects

Store your list as an array in state, where each item is an object with its own fields:

const [addresses, setAddresses] = useState([
  { street: '', city: '', zip: '' }
]);

Each address has multiple fields, and you'll need functions to:

  1. Add items: Append a new object to the array
  2. Remove items: Filter out an item by index
  3. Update items: Replace a specific item's field value

Updating Array Items Immutably

When a field in the third address changes, you must create a new array with that one object replaced:

const updateAddress = (index, field, value) => {
  setAddresses(prev => prev.map((addr, i) => 
    i === index ? { ...addr, [field]: value } : addr
  ));
};

This maps over the array, spreading the matching item with the updated field.

Adding and Removing

const addAddress = () => {
  setAddresses(prev => [...prev, { street: '', city: '', zip: '' }]);
};

const removeAddress = (index) => {
  setAddresses(prev => prev.filter((_, i) => i !== index));
};

Key Takeaway: Dynamic form sections require array state with immutable update patterns—map to modify items, spread to add, and filter to remove—keeping each item as a structured object.