Assessing Form Generation
I'm currently focused on the overarching goal: constructing a sophisticated React form generator. I've broken down the project into digestible chunks, initially prioritizing drag-and-drop field arrangement and diverse field type inclusion. My next steps involve exploring the optimal implementation strategy for the preview mode, which needs to be seamlessly integrated.
Outlining Form State
I've been drilling down on the fundamental state representation for the form. I'm leaning toward employing useState and useReducer to manage the dynamic list of form fields. This will also help me keep track of a few key technologies I'll be using, like dnd-kit for drag-and-drop and lucide-react for icons. I've also decided to use Tailwind CSS for the overall look and feel. Lastly, I'm thinking of using react-hook-form to handle the submissions.
Implementing Field Properties
My focus has shifted to allowing configuration of the form fields. I'm exploring an inline editing approach for simplicity, letting users modify labels and required status directly. The JSON preview is also proving useful to visualize the output. I've defined a clear data structure for the fields, including their types, labels, and various properties. I've begun setting up dnd-kit, using SortableContext and sensors. The goal is to seamlessly integrate dragging fields from a sidebar.
Prioritizing Core Functionality
I'm now focusing on a streamlined implementation strategy. I'm prioritizing adding fields via clicking and sorting them within the form builder, to keep the initial code manageable. I'm focusing on building the Sidebar, FieldCard, and FormBuilder components. I plan to refine the drag-and-drop logic using SortableContext and useSortable, employing arrayMove for updating the field order. I'm also preparing for dynamic rendering based on the field type and inline editing features for properties.
Addressing Drag Issues
I've been working on refining the drag-and-drop interactions to prevent accidental focus changes when editing field labels. I'm now implementing drag handles to improve the user experience. Styling has become important, and I'm designing a layout similar to modern SaaS tools, with a sidebar on the left, the form canvas in the middle, and a preview on the right. Finally, I'm setting up the core elements, including component setup, the actual sorting logic using handleDragEnd, and a way to preview the form—I've decided on a "Live Form" view.
Integrating Select Field
I'm now integrating the "Select" field to showcase handling of more complex options. This involves defining the field's data structure, implementing the user interface for option management, and seamlessly integrating it with the drag-and-drop functionality. My next step will be to ensure this field type works smoothly within the existing framework and properly serializes its options for the final form output. I'm also ensuring full React and dnd-kit compliance.
This is a complete, functional example of a Form Generator using React, Target CSS for styling, and @dnd-kit for the drag-and-drop functionality.
@dnd-kit is currently the industry standard for React drag-and-drop because it is lightweight, accessible (keyboard support), and modular.
Prerequisites
You will need to install the following dependencies:
npm install @dnd-kit/core @dnd-kit/sortable @dnd-kit/utilities lucide-react clsx tailwind-merge
The Complete Solution
I have combined everything into a single logic flow for clarity, but in a real app, you would split these into separate files.
import React, { useState } from 'react';
import {
DndContext,
closestCenter,
KeyboardSensor,
PointerSensor,
useSensor,
useSensors,
DragEndEvent,
} from '@dnd-kit/core';
import {
arrayMove,
SortableContext,
sortableKeyboardCoordinates,
verticalListSortingStrategy,
useSortable,
} from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import {
GripVertical,
Trash2,
Plus,
Type,
Hash,
List,
CheckSquare,
AlertCircle
} from 'lucide-react';
// --- Types ---
type FieldType = 'text' | 'number' | 'textarea' | 'select' | 'checkbox';
interface FormField {
id: string;
type: FieldType;
label: string;
placeholder?: string;
required: boolean;
options?: string[]; // Used for select inputs
}
// --- Helper Components ---
// 1. The Sidebar Item (Draggable Templates)
const SidebarBtn = ({ type, icon: Icon, label, onClick }: any) => (
<button
onClick={onClick}
className="flex items-center gap-2 w-full p-3 mb-2 bg-white border border-gray-200 rounded-lg hover:bg-blue-50 hover:border-blue-300 transition-all shadow-sm group"
>
<Icon className="w-4 h-4 text-gray-500 group-hover:text-blue-600" />
<span className="text-sm font-medium text-gray-700 group-hover:text-blue-700">{label}</span>
<Plus className="w-4 h-4 ml-auto text-gray-300 opacity-0 group-hover:opacity-100" />
</button>
);
// 2. The Sortable Field Item (The card on the canvas)
interface SortableFieldProps {
field: FormField;
onDelete: (id: string) => void;
onUpdate: (id: string, updates: Partial<FormField>) => void;
}
const SortableField = ({ field, onDelete, onUpdate }: SortableFieldProps) => {
const {
attributes,
listeners,
setNodeRef,
transform,
transition,
isDragging,
} = useSortable({ id: field.id });
const style = {
transform: CSS.Transform.toString(transform),
transition,
zIndex: isDragging ? 100 : 1, // Ensure dragged item is on top
};
return (
<div
ref={setNodeRef}
style={style}
className={`relative p-4 mb-3 bg-white border rounded-lg shadow-sm group ${
isDragging ? 'border-blue-500 ring-2 ring-blue-200 opacity-80' : 'border-gray-200 hover:border-gray-300'
}`}
>
{/* Drag Handle */}
<div
{...attributes}
{...listeners}
className="absolute left-2 top-1/2 -translate-y-1/2 p-2 cursor-grab text-gray-300 hover:text-gray-600 active:cursor-grabbing"
>
<GripVertical className="w-5 h-5" />
</div>
{/* Field Content */}
<div className="pl-8 pr-8">
<div className="flex gap-3 mb-3">
<div className="flex-1">
<label className="block text-xs font-semibold text-gray-500 uppercase mb-1">Label</label>
<input
type="text"
value={field.label}
onChange={(e) => onUpdate(field.id, { label: e.target.value })}
className="w-full px-2 py-1 text-sm border border-gray-300 rounded focus:outline-none focus:border-blue-500"
/>
</div>
<div className="w-1/3">
<label className="block text-xs font-semibold text-gray-500 uppercase mb-1">Type</label>
<div className="px-2 py-1 text-sm bg-gray-50 text-gray-600 rounded border border-gray-200 capitalize">
{field.type}
</div>
</div>
</div>
{/* Conditional Options for 'Select' type */}
{field.type === 'select' && (
<div className="mb-3">
<label className="block text-xs font-semibold text-gray-500 uppercase mb-1">
Options (comma separated)
</label>
<input
type="text"
value={field.options?.join(', ') || ''}
onChange={(e) => onUpdate(field.id, { options: e.target.value.split(',').map(s => s.trim()) })}
className="w-full px-2 py-1 text-sm border border-gray-300 rounded focus:outline-none focus:border-blue-500"
placeholder="Option 1, Option 2..."
/>
</div>
)}
<div className="flex items-center gap-4 pt-2 border-t border-gray-100">
<label className="flex items-center gap-2 cursor-pointer">
<input
type="checkbox"
checked={field.required}
onChange={(e) => onUpdate(field.id, { required: e.target.checked })}
className="w-4 h-4 text-blue-600 rounded focus:ring-blue-500"
/>
<span className="text-sm text-gray-600">Required</span>
</label>
{/* Validation Hint (Visual feedback only) */}
{field.required && <span className="text-xs text-red-500 flex items-center gap-1"><AlertCircle size={10}/> Mandatory</span>}
</div>
</div>
{/* Delete Button */}
<button
onClick={() => onDelete(field.id)}
className="absolute right-2 top-2 p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-md transition-colors"
>
<Trash2 className="w-4 h-4" />
</button>
</div>
);
};
// --- Main Generator Component ---
export default function FormBuilder() {
const [fields, setFields] = useState<FormField[]>([]);
// DnD Sensors
const sensors = useSensors(
useSensor(PointerSensor),
useSensor(KeyboardSensor, {
coordinateGetter: sortableKeyboardCoordinates,
})
);
// Actions
const addField = (type: FieldType) => {
const newField: FormField = {
id: `field-${Date.now()}`,
type,
label: `New ${type} field`,
required: false,
options: type === 'select' ? ['Option 1', 'Option 2'] : undefined,
};
setFields((prev) => [...prev, newField]);
};
const removeField = (id: string) => {
setFields((prev) => prev.filter((f) => f.id !== id));
};
const updateField = (id: string, updates: Partial<FormField>) => {
setFields((prev) =>
prev.map((f) => (f.id === id ? { ...f, ...updates } : f))
);
};
const handleDragEnd = (event: DragEndEvent) => {
const { active, over } = event;
if (active.id !== over?.id) {
setFields((items) => {
const oldIndex = items.findIndex((item) => item.id === active.id);
const newIndex = items.findIndex((item) => item.id === over?.id);
return arrayMove(items, oldIndex, newIndex);
});
}
};
return (
<div className="min-h-screen bg-gray-50 flex flex-col">
<header className="bg-white border-b px-6 py-4 flex justify-between items-center sticky top-0 z-10">
<h1 className="text-xl font-bold text-gray-800 flex items-center gap-2">
<List className="text-blue-600" />
React Form Generator
</h1>
<button
className="px-4 py-2 bg-blue-600 text-white text-sm font-medium rounded-lg hover:bg-blue-700 transition-colors"
onClick={() => alert(JSON.stringify(fields, null, 2))}
>
Save Schema
</button>
</header>
<div className="flex-1 flex overflow-hidden">
{/* Sidebar: Toolset */}
<aside className="w-64 bg-white border-r p-4 overflow-y-auto">
<h2 className="text-xs font-semibold text-gray-400 uppercase tracking-wider mb-4">Components</h2>
<div className="space-y-2">
<SidebarBtn type="text" label="Text Input" icon={Type} onClick={() => addField('text')} />
<SidebarBtn type="textarea" label="Text Area" icon={List} onClick={() => addField('textarea')} />
<SidebarBtn type="number" label="Number" icon={Hash} onClick={() => addField('number')} />
<SidebarBtn type="select" label="Dropdown" icon={CheckSquare} onClick={() => addField('select')} />
<SidebarBtn type="checkbox" label="Checkbox" icon={CheckSquare} onClick={() => addField('checkbox')} />
</div>
</aside>
{/* Main Canvas: Builder Area */}
<main className="flex-1 p-8 bg-gray-50 overflow-y-auto">
<div className="max-w-2xl mx-auto">
<div className="mb-6">
<h2 className="text-2xl font-bold text-gray-800 mb-2">Form Canvas</h2>
<p className="text-gray-500">Drag and drop fields to rearrange. Click properties to edit.</p>
</div>
{fields.length === 0 ? (
<div className="border-2 border-dashed border-gray-300 rounded-xl p-12 text-center hover:border-blue-400 transition-colors">
<p className="text-gray-400">Your form is empty. Add fields from the sidebar.</p>
</div>
) : (
<DndContext
sensors={sensors}
collisionDetection={closestCenter}
onDragEnd={handleDragEnd}
>
<SortableContext
items={fields.map((f) => f.id)}
strategy={verticalListSortingStrategy}
>
<div className="space-y-3 pb-20">
{fields.map((field) => (
<SortableField
key={field.id}
field={field}
onDelete={removeField}
onUpdate={updateField}
/>
))}
</div>
</SortableContext>
</DndContext>
)}
</div>
</main>
{/* Preview Panel: Live Render */}
<aside className="w-80 bg-white border-l flex flex-col h-full">
<div className="p-4 border-b bg-gray-50">
<h2 className="text-sm font-semibold text-gray-700">Live Preview</h2>
</div>
<div className="p-4 flex-1 overflow-y-auto">
<form className="space-y-4" onSubmit={(e) => e.preventDefault()}>
{fields.map((field) => (
<div key={field.id}>
<label className="block text-sm font-medium text-gray-700 mb-1">
{field.label}
{field.required && <span className="text-red-500 ml-1">*</span>}
</label>
{field.type === 'textarea' ? (
<textarea
className="w-full px-3 py-2 border rounded-md text-sm"
placeholder={field.placeholder}
required={field.required}
/>
) : field.type === 'select' ? (
<select className="w-full px-3 py-2 border rounded-md text-sm" required={field.required}>
{field.options?.map((opt, i) => <option key={i}>{opt}</option>)}
</select>
) : field.type === 'checkbox' ? (
<input type="checkbox" className="w-4 h-4 text-blue-600 rounded" />
) : (
<input
type={field.type}
className="w-full px-3 py-2 border rounded-md text-sm"
placeholder={field.placeholder}
required={field.required}
/>
)}
</div>
))}
{fields.length > 0 && (
<button className="w-full bg-blue-600 text-white py-2 px-4 rounded-md text-sm hover:bg-blue-700 mt-4">
Submit Form
</button>
)}
</form>
</div>
</aside>
</div>
</div>
);
}
Key Features Explained
-
Data Structure (FormField interface)
Each field represents a JSON object containing an id, type, label, and validation rules. This makes it easy to serialize the form to a database and re-generate it later.
-
Drag and Drop Logic (dnd-kit)
- DndContext: The wrapper that monitors pointer sensor events (mouse/touch) and detects when a drag ends.
- SortableContext: Wraps the list of items. It tells the library that these items can be reordered vertically.
- useSortable: This hook is used inside the individual component (
SortableField). It provides:
listeners: Event handlers (like onMouseDown) attached to the drag handle.
transform: CSS coordinates to move the item visually while dragging.
transition: Makes the movement smooth when items swap places.
-
Separate Sorting from Editing
Notice the Drag Handle (<GripVertical />). We attach the drag listeners only to this handle, not the whole card. This is crucial for complex forms. If you attach drag listeners to the entire card, the user won't be able to click into the Inputs to edit the label without accidentally dragging the card.
-
Live Preview
The right sidebar renders a standard HTML form based on the current fields state array. This gives immediate feedback to the user on what their end-users will see.
How to Extend
To make this production-ready:
- Nested Structures: If you need rows with multiple columns, you will need to update the data structure to support children and use nested
SortableContexts.
- React Hook Form: In the "Live Preview" or the actual rendered form, integrate
react-hook-form for robust validation handling.
- Drag from Sidebar: Currently, you click sidebar items to append them. To drag from the sidebar into the sortable list, use
useDraggable on sidebar items and a DragOverlay component in the main context.