Tips & Tricks

Claude Code के साथ Implement Drag and Drop कैसे करें

Claude Code का उपयोग करके implement drag and drop सीखें। Practical code examples और step-by-step guidance शामिल है।

ドラッグ&ドロップのimplementationpattern

ドラッグ&ドロップは直感的なUIを実現するimportantなfeatures है।list並べ替え、カンバンボード、fileupload आदि多くの場面で使われ है।Claude Code का उपयोग करके、アクセシブルでrobustなドラッグ&ドロップを効率よくimplementationでき है।

カスタムhookによる基本implementation

> HTML Drag and Drop APIを使ったReactのカスタムhookを作って。
> listの並べ替えにsupportして。
import { useState, useCallback, DragEvent } from 'react';

function useSortable<T extends { id: string }>(initialItems: T[]) {
  const [items, setItems] = useState(initialItems);
  const [draggedId, setDraggedId] = useState<string | null>(null);

  const handleDragStart = useCallback((e: DragEvent, id: string) => {
    setDraggedId(id);
    e.dataTransfer.effectAllowed = 'move';
    e.dataTransfer.setData('text/plain', id);
  }, []);

  const handleDragOver = useCallback((e: DragEvent, targetId: string) => {
    e.preventDefault();
    e.dataTransfer.dropEffect = 'move';

    if (draggedId === null || draggedId === targetId) return;

    setItems((prev) => {
      const dragIndex = prev.findIndex((item) => item.id === draggedId);
      const targetIndex = prev.findIndex((item) => item.id === targetId);
      const newItems = [...prev];
      const [removed] = newItems.splice(dragIndex, 1);
      newItems.splice(targetIndex, 0, removed);
      return newItems;
    });
  }, [draggedId]);

  const handleDragEnd = useCallback(() => {
    setDraggedId(null);
  }, []);

  return { items, draggedId, handleDragStart, handleDragOver, handleDragEnd, setItems };
}

sortpossibleなlistcomponent

function SortableList({ initialTasks }: { initialTasks: Task[] }) {
  const { items, draggedId, handleDragStart, handleDragOver, handleDragEnd } =
    useSortable(initialTasks);

  return (
    <ul role="listbox" aria-label="tasklist(並べ替えpossible)">
      {items.map((task) => (
        <li
          key={task.id}
          draggable
          role="option"
          aria-grabbed={draggedId === task.id}
          onDragStart={(e) => handleDragStart(e, task.id)}
          onDragOver={(e) => handleDragOver(e, task.id)}
          onDragEnd={handleDragEnd}
          className={`p-3 mb-2 rounded border cursor-grab ${
            draggedId === task.id ? 'opacity-50 border-blue-400' : 'border-gray-200'
          }`}
        >
          <span>{task.title}</span>
        </li>
      ))}
    </ul>
  );
}

fileドロップゾーン

> fileをドラッグ&ドロップでuploadできるcomponentを作って。
> previewdisplayとvalidationも。
function FileDropZone({ onFiles, accept, maxSize = 5 * 1024 * 1024 }: DropZoneProps) {
  const [isDragging, setIsDragging] = useState(false);
  const [errors, setErrors] = useState<string[]>([]);

  const validateFiles = (files: File[]): File[] => {
    const errs: string[] = [];
    const valid = files.filter((file) => {
      if (accept && !accept.includes(file.type)) {
        errs.push(`${file.name}: supportしていないfile形式です`);
        return false;
      }
      if (file.size > maxSize) {
        errs.push(`${file.name}: filesizeがऊपर限を超えています`);
        return false;
      }
      return true;
    });
    setErrors(errs);
    return valid;
  };

  const handleDrop = (e: DragEvent<HTMLDivElement>) => {
    e.preventDefault();
    setIsDragging(false);
    const files = Array.from(e.dataTransfer.files);
    const valid = validateFiles(files);
    if (valid.length > 0) onFiles(valid);
  };

  return (
    <div
      onDragOver={(e) => { e.preventDefault(); setIsDragging(true); }}
      onDragLeave={() => setIsDragging(false)}
      onDrop={handleDrop}
      className={`border-2 border-dashed rounded-lg p-8 text-center transition-colors ${
        isDragging ? 'border-blue-500 bg-blue-50' : 'border-gray-300'
      }`}
    >
      <p>fileをयहांにドロップ、またはクリックして選択</p>
      {errors.map((err, i) => (
        <p key={i} className="text-red-500 text-sm mt-1">{err}</p>
      ))}
    </div>
  );
}

keyボード操作のサポート

accessibility के लिएにkeyボードでも操作できる तरहし है।

const handleKeyDown = (e: React.KeyboardEvent, index: number) => {
  if (e.key === ' ' || e.key === 'Enter') {
    e.preventDefault();
    toggleGrabbed(index);
  }
  if (e.key === 'ArrowUp' && isGrabbed) {
    e.preventDefault();
    moveItem(index, index - 1);
  }
  if (e.key === 'ArrowDown' && isGrabbed) {
    e.preventDefault();
    moveItem(index, index + 1);
  }
};

Summary

Claude Code का उपयोग करके、list並べ替え सेfileupload तक、多様なドラッグ&ドロップimplementationをefficientlybuild किया जा सकता है。fileuploadके details के लिएfileuploadimplementationを、accessibilitysupportはaccessibilityガイドをदेखें。

HTML Drag and Drop APIの仕様はMDN Web Docsदेखें。

#Claude Code #drag and drop #React #UI #interaction
मुफ़्त

मुफ़्त PDF: 5 मिनट में Claude Code चीटशीट

बस अपना ईमेल दर्ज करें और हम तुरंत A4 एक-पृष्ठ चीटशीट PDF भेज देंगे।

हम आपकी व्यक्तिगत जानकारी की सुरक्षा करते हैं और स्पैम नहीं भेजते।

Masa

लेखक के बारे में

Masa

Claude Code का गहराई से उपयोग करने वाले इंजीनियर। claudecode-lab.com चलाते हैं, जो 10 भाषाओं में 2,000 से अधिक पेजों वाला टेक मीडिया है।