Created
July 9, 2019 14:07
-
-
Save questionmarcus/c677064db21ce5369a961ac3793ec43c to your computer and use it in GitHub Desktop.
React Draggable Example — Sk8er boi
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { DragEvent } from "react"; | |
const chorus = [ | |
"He was a sk8er boi", | |
"She needed to come back down to Earth", | |
"She had a pretty face but her head was up in space", | |
"She said see you later boy", | |
"He wasn't good enough for her" | |
]; | |
interface State { | |
lyrics: string[]; | |
} | |
class App extends React.Component<{}, State> { | |
state = { | |
lyrics: chorus | |
}; | |
onDragStart = (e: DragEvent<HTMLLIElement>, ind: number) => { | |
// Data transfer can only handle strings, but we can state a custom MIME type | |
e.dataTransfer.setData("application/index", `${ind}`); | |
}; | |
onDrop = (e: DragEvent<HTMLLIElement>, ind: number) => { | |
const targetInd = ind; | |
const sourceInd = parseInt(e.dataTransfer.getData("application/index")); | |
this.setState(oldState => { | |
const newLyrics = [...oldState.lyrics]; | |
// Swap the elements around | |
const tmp = newLyrics[targetInd]; | |
newLyrics[targetInd] = newLyrics[sourceInd]; | |
newLyrics[sourceInd] = tmp; | |
return { | |
lyrics: newLyrics | |
}; | |
}); | |
}; | |
render() { | |
return ( | |
<> | |
<h1>Are you a Sk8er boi!?</h1> | |
<h4>Drag the lyrics around and put them in the right order!</h4> | |
<ul> | |
{this.state.lyrics.map((line, ind) => ( | |
<li | |
key={`ind`} | |
draggable | |
onDragStart={e => this.onDragStart(e, ind)} | |
onDragOver={e => e.preventDefault()} | |
onDrop={e => this.onDrop(e, ind)} | |
> | |
{line} | |
</li> | |
))} | |
</ul> | |
</> | |
); | |
} | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment