React DnD Preview Component

9.0.0 · active · verified Sun Apr 19

react-dnd-preview is a dedicated component for creating drag-and-drop previews within applications utilizing React DnD. It simplifies the implementation of visual feedback during drag operations by providing a component that renders the dragged item at the current mouse position. The current stable version is 9.0.0, which includes support for React v19. Releases typically follow the React and React DnD release cycles for major versions, with minor and patch updates for bug fixes and dependency bumps occurring more frequently. Its key differentiator is its tight integration with the React DnD ecosystem, offering a straightforward way to add preview functionality without complex manual DOM manipulation, making it an essential companion for sophisticated drag-and-drop UIs.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates a basic draggable box with a custom preview generated by `react-dnd-preview`, using `DndProvider` and `HTML5Backend`.

import React from 'react';
import { DndProvider } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';
import { useDrag } from 'react-dnd';
import { Preview } from 'react-dnd-preview';

const DraggableBox: React.FC = () => {
  const [{ isDragging }, drag] = useDrag(() => ({
    type: 'BOX',
    item: { id: 'some-item' },
    collect: (monitor) => ({
      isDragging: monitor.isDragging()
    })
  }));

  return (
    <div
      ref={drag}
      style={{
        opacity: isDragging ? 0.5 : 1,
        cursor: 'move',
        width: '100px',
        height: '100px',
        border: '1px solid black',
        backgroundColor: 'lightblue',
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center'
      }}
    >
      Drag Me
    </div>
  );
};

const generatePreview = ({ itemType, item, style }) => {
  if (itemType === 'BOX') {
    return (
      <div style={{ ...style, backgroundColor: 'orange', padding: '10px', borderRadius: '5px' }}>
        Previewing {item.id}
      </div>
    );
  }
  return null;
};

const App: React.FC = () => {
  return (
    <DndProvider backend={HTML5Backend}>
      <div style={{ padding: '20px' }}>
        <h1>React DnD Preview Example</h1>
        <DraggableBox />
        <Preview generator={generatePreview} />
      </div>
    </DndProvider>
  );
};

export default App;

view raw JSON →