Blog>
Snippets

Dynamic Form Field Creation

Illustrate dynamic form field creation where fields are added or removed based on user actions using `createReducer`.
import { createAction, createReducer } from '@reduxjs/toolkit';

// Actions to add and remove form fields
const addField = createAction('form/addField');
const removeField = createAction('form/removeField');

// Initial state of the form
const initialState = {
    fields: []
};

// Reducer handling the addition and removal of form fields
const formReducer = createReducer(initialState, (builder) => {
    builder
        .addCase(addField, (state, action) => {
            // Add a new field with a unique id to the fields array
            const field = { id: Date.now(), ...action.payload };
            state.fields.push(field);
        })
        .addCase(removeField, (state, action) => {
            // Remove the field with the specified id from the fields array
            state.fields = state.fields.filter(field => field.id !== action.payload.id);
        });
});

export default formReducer;
Defines actions and a reducer for dynamically adding and removing fields in a form. The reducer listens for addField and removeField actions and modifies the fields array in the state.
// Component example using the above reducer
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { addField, removeField } from './formReducer';

const DynamicForm = () => {
    const fields = useSelector(state => state.form.fields);
    const dispatch = useDispatch();

    const handleAddField = () => {
        dispatch(addField({ type: 'text', placeholder: 'Enter text' }));
    };

    const handleRemoveField = (id) => {
        dispatch(removeField({ id }));
    };

    return (
        <div>
            {fields.map(field => (
                <div key={field.id}>
                    <input type={field.type} placeholder={field.placeholder} />
                    <button onClick={() => handleRemoveField(field.id)}>Remove</button>
                </div>
            ))}
            <button onClick={handleAddField}>Add Field</button>
        </div>
    );
};

export default DynamicForm;
Component example using Redux to dynamically add and remove input fields in a form. Utilizes useSelector to get the current fields and useDispatch to dispatch the addField and removeField actions.