Skip to content

Instantly share code, notes, and snippets.

@rolangom
Created June 2, 2017 05:46
Show Gist options
  • Save rolangom/c3a037e51a80d12e2656b46ffd3dc9d8 to your computer and use it in GitHub Desktop.
Save rolangom/c3a037e51a80d12e2656b46ffd3dc9d8 to your computer and use it in GitHub Desktop.
RNGridListView: React Native Selectable Grid in a ListView
import React, { Component } from 'react';
import { Text, View, StyleSheet, VirtualizedList, Dimensions, TouchableOpacity } from 'react-native';
import { Constants } from 'expo';
const arrItems = 'Q,W,E,R,T,Y,U,I,O,P,A,S,D,F,G,H,J,K,L,Z,X,C,V,B,N,M,1,2,3,4,5,6,7,8,9,0'.split(',').map(it => ({key: it}));
const Item = ({item, width, selectedItems, setItem}) => {
const isActive = selectedItems.indexOf(item.key) > -1;
return (
<TouchableOpacity
onPress={() => setItem(item.key, !isActive)}
style={[styles.item, {width}, isActive ? styles.activeItem : null]}>
<Text>{item.key}</Text>
</TouchableOpacity>
);
};
export default class App extends Component {
state = { selectedItems: [] };
setItem = (key, added) => {
console.log('key, added?', key, added);
if (added) {
this.setState({ selectedItems: this.state.selectedItems.concat(key) });
} else { // Remove action
const index = this.state.selectedItems.indexOf(key);
if (index > -1) {
const tmplist = this.state.selectedItems;
tmplist.splice(index, 1);
this.setState({ selectedItems: tmplist });
}
}
}
render() {
const { height, width } = Dimensions.get('window');
return (
<View style={styles.container}>
<Text style={styles.paragraph}>
RNGridListView
</Text>
<VirtualizedList
contentContainerStyle={styles.list}
data={arrItems}
renderItem={({item}) =>
<Item
item={item}
setItem={this.setItem}
width={width/3 - 10}
selectedItems={this.state.selectedItems}
/>}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
},
paragraph: {
margin: 24,
fontSize: 18,
fontWeight: 'bold',
textAlign: 'center',
color: '#34495e',
},
list: {
flexDirection: 'row',
flexWrap: 'wrap',
justifyContent: 'space-around',
paddingHorizontal: 5,
},
item: {
backgroundColor: '#DEF',
alignItems: 'center',
justifyContent: 'center',
marginBottom: 5,
padding: 5,
width: 100, // value will be overriten
height: 90,
},
activeItem: {
backgroundColor: '#CDE',
}
});
@rolangom
Copy link
Author

rolangom commented Jun 2, 2017

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment