Skip to content

Instantly share code, notes, and snippets.

@deanmcpherson
Created July 12, 2016 23:21
Show Gist options
  • Save deanmcpherson/83d22b894292a7718004d280cb4b9765 to your computer and use it in GitHub Desktop.
Save deanmcpherson/83d22b894292a7718004d280cb4b9765 to your computer and use it in GitHub Desktop.
Example of sortable that persists over logins.
let SortableListView = require('./SortableListView');
let React = require('react-native');
let {
View,
Text,
TouchableHighlight,
AsyncStorage
} = React;
const DATA = 'DATA';
var data = {
hello: {text: 'world'},
how: {text: 'are you'},
test: {text: 123},
this: {text: 'is'},
a: {text: 'a'},
real: {text: 'real'},
drag: {text: 'drag and drop'},
bb: {text: 'bb'},
cc: {text: 'cc'},
dd: {text: 'dd'},
ee: {text: 'ee'},
ff: {text: 'ff'},
gg: {text: 'gg'},
hh: {text: 'hh'},
ii: {text: 'ii'},
jj: {text: 'jj'},
kk: {text: 'kk'}
}
let order = Object.keys(data); //Array of keys
let RowComponent = React.createClass({
render: function() {
return <TouchableHighlight underlayColor={'#eee'} style={{padding: 25, backgroundColor: "#F8F8F8", borderBottomWidth:1, borderColor: '#eee'}} {...this.props.sortHandlers}>
<Text>{this.props.data.text}</Text>
</TouchableHighlight>
}
})
let MyComponent = React.createClass({
componentWillMount: function() {
AsyncStorage.getItem(DATA).then(res => {
if (res) {
let state = JSON.parse(res);
return this.setState(state);
}
this.setState({
data, order
})
})
},
getInitialState: function() {
return {}
},
componentDidUpdate: function(props, state) {
if (state.data) {
AsyncStorage.setItem(DATA, JSON.stringify(state));
}
},
render: function() {
if (!this.state.data) return <View />;
return <SortableListView
style={{flex: 1}}
data={this.state.data}
order={this.state.order}
onRowMoved={e => {
order.splice(e.to, 0, order.splice(e.from, 1)[0]);
this.forceUpdate();
}}
renderRow={row => <RowComponent data={row} />}
/>
}
});
module.exports = MyComponent;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment