Blog>
Snippets

Dynamic Form Fields with useReducer

Create a form that allows users to dynamically add or remove input fields using useReducer to handle complex state changes.
import React, { useReducer } from 'react';
Import React and the useReducer hook.
const initialState = [{ id: Date.now(), value: '' }];
Define the initial state for our form as an array with an initial input field object.
function reducer(state, action) {
  switch (action.type) {
    case 'add':
      return [...state, { id: Date.now(), value: '' }];
    case 'remove':
      return state.filter(field => field.id !== action.id);
    case 'change':
      return state.map(field =>
        field.id === action.id ? { ...field, value: action.value } : field
      );
    default:
      return state;
  }
}
Define a reducer function to manage the state changes for adding, removing, and changing input fields.
function DynamicFormFields() {
  const [fields, dispatch] = useReducer(reducer, initialState);

  const handleAdd = () => {
    dispatch({ type: 'add' });
  };

  const handleRemove = id => {
    dispatch({ type: 'remove', id });
  };

  const handleChange = (id, event) => {
    dispatch({ type: 'change', id, value: event.target.value });
  };

  const handleSubmit = event => {
    event.preventDefault();
    // Submit logic would go here
  };

  return (
    <form onSubmit={handleSubmit}>
      {fields.map(field => (
        <div key={field.id}>
          <input
            type='text'
            value={field.value}
            onChange={event => handleChange(field.id, event)}
          />
          <button type='button' onClick={() => handleRemove(field.id)}>
            Remove
          </button>
        </div>
      ))}
      <button type='button' onClick={handleAdd}>Add Field</button>
      <button type='submit'>Submit</button>
    </form>
  );
}
The DynamicFormFields functional component uses the useReducer hook to update the fields array. It includes handlers for adding, removing, and changing input fields, as well as a handleSubmit function for form submission.