Skip to content

Instantly share code, notes, and snippets.

@sherzader
Last active June 17, 2020 17:29
Show Gist options
  • Select an option

  • Save sherzader/34aba442f567c7bc6832c69399e1092b to your computer and use it in GitHub Desktop.

Select an option

Save sherzader/34aba442f567c7bc6832c69399e1092b to your computer and use it in GitHub Desktop.
import React from "react"
import ReactDOM from "react-dom"
class App extends React.PureComponent {
state = { blocks: {} }
handleDragStart = (e) => {
// find block in blocks and set isDragging property to true
const blockId = e.target.dataset.id
const block = { ...this.state.blocks[blockId] }
block.isDragging = true
this.setState({ blocks: { ...this.state.blocks, [blockId]: block } })
}
handleDragging = (e) => {
// find block in blocks and if isDragging updating position
const blockId = e.target.dataset.id
const block = { ...this.state.blocks[blockId] }
if (!block.isDragging) {
return
}
block.left = e.clientX
block.top = e.clientY
this.setState({ blocks: { ...this.state.blocks, [blockId]: block } })
}
handleDragEnd = (e) => {
// find block in blocks, update position, and set isDragging back to false
const blockId = e.target.dataset.id
const block = { ...this.state.blocks[blockId] }
block.left = e.clientX
block.top = e.clientY
// set isDragging to false for block
block.isDragging = false
this.setState({ blocks: { ...this.state.blocks, [blockId]: block } })
}
render() {
return (
<div style={{ display: "flex", flexDirection: "column", height: "100%" }}>
<div>
<button onClick={this.handleNewBlock}>new block</button>
</div>
<div style={{ display: "flex" }}>
{Object.values(this.state.blocks).map(
({ id, height, width, left, top }) => (
<div
key={id}
data-id={id}
draggable="true"
onDragEnter={this.handleDragStart}
onDrag={this.handleDragging}
onDragEnd={this.handleDragEnd}
style={{
position: "absolute",
border: "1px solid black",
height,
width,
left,
top,
}}
/>
)
)}
</div>
</div>
)
}
handleNewBlock = () => {
const { blocks } = this.state
const newBlock = {
id: Math.random(),
width: 100,
height: 100,
left: window.innerWidth / 2 - 50,
top: window.innerHeight / 2 - 50,
isDragging: false,
}
this.setState({ blocks: { ...blocks, [newBlock.id]: newBlock } })
}
}
ReactDOM.render(<App />, document.getElementById("root"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment