Skip to content

Instantly share code, notes, and snippets.

@tfiechowski
Last active October 30, 2019 09:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tfiechowski/09fe6aebec1d60c8090a143b81d227ed to your computer and use it in GitHub Desktop.
Save tfiechowski/09fe6aebec1d60c8090a143b81d227ed to your computer and use it in GitHub Desktop.
import React, { Component, createContext } from "react";
import sampleItems from './sampleItems';
// Helper functions
function move(array, oldIndex, newIndex) {
if (newIndex >= array.length) {
newIndex = array.length - 1;
}
array.splice(newIndex, 0, array.splice(oldIndex, 1)[0]);
return array;
}
function moveElement(array, index, offset) {
const newIndex = index + offset;
return move(array, index, newIndex);
}
// Context
const GridContext = createContext({ items: [] });
export class GridProvider extends Component {
constructor(props) {
super(props);
this.state = {
items: sampleItems,
moveItem: this.moveItem,
setItems: this.setItems
};
}
render() {
return (
<GridContext.Provider value={this.state}>
{this.props.children}
</GridContext.Provider>
);
}
setItems = items => this.setState({ items });
moveItem = (sourceId, destinationId) => {
const sourceIndex = this.state.items.findIndex(
item => item.id === sourceId
);
const destinationIndex = this.state.items.findIndex(
item => item.id === destinationId
);
// If source/destination is unknown, do nothing.
if (sourceId === -1 || destinationId === -1) {
return;
}
const offset = destinationIndex - sourceIndex;
this.setState(state => ({
items: moveElement(state.items, sourceIndex, offset)
}));
};
}
export default GridContext;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment