프로그래밍/Script
[React] DnD - Drag andDrop for React
홍반장水_
2022. 9. 8. 11:24
반응형
[React] DnD - Drag andDrop for React
https://react-dnd.github.io/react-dnd/about
React DnD
react-dnd.github.io
React DnD is a set of React utilities to help you build complex drag and drop interfaces while keeping your components decoupled. It is a perfect fit for apps like Trello and Storify, where dragging transfers data between different parts of the application, and the components change their appearance and the application state in response to the drag and drop events.
Installation
npm install react-dnd react-dnd-html5-backend
The second package will allow React DnD the HTML5 drag and drop API under the hood. You may choose to use a third-party backend instead, such as the touch backend.
// Let's make <Card text='Write the docs' /> draggable!
import React from 'react'
import { useDrag } from 'react-dnd'
import { ItemTypes } from './Constants'
/**
* Your Component
*/
export default function Card({ isDragging, text }) {
const [{ opacity }, dragRef] = useDrag(
() => ({
type: ItemTypes.CARD,
item: { text },
collect: (monitor) => ({
opacity: monitor.isDragging() ? 0.5 : 1
})
}),
[]
)
return (
<div ref={dragRef} style={{ opacity }}>
{text}
</div>
)
}
react-dnd-example-3 - CodeSandbox
auto-generated package for codesandbox import
codesandbox.io
반응형