Skip to content

Instantly share code, notes, and snippets.

@questionmarcus
Created July 9, 2019 14:07
Show Gist options
  • Save questionmarcus/c677064db21ce5369a961ac3793ec43c to your computer and use it in GitHub Desktop.
Save questionmarcus/c677064db21ce5369a961ac3793ec43c to your computer and use it in GitHub Desktop.
React Draggable Example — Sk8er boi
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