forked from christopherabouabdo/react-native-photo-grid
-
Notifications
You must be signed in to change notification settings - Fork 2
/
PhotoGrid.js
72 lines (59 loc) · 1.72 KB
/
PhotoGrid.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
'use strict';
import React, { Component } from 'react';
import {
Dimensions,
ListView,
StyleSheet,
View,
} from 'react-native';
let styles = StyleSheet.create({
row: {
flex: 1,
flexDirection: 'row',
justifyContent: 'space-between',
}
});
class PhotoGrid extends React.Component {
constructor() {
super();
this.state = {
data: new ListView.DataSource({
rowHasChanged: (r1, r2) => { r1 !== r2; }
}),
}
}
buildRows(items, itemsPerRow = 3) {
return items.reduce((rows, item, idx) => {
// If a full row is filled create a new row array
if(idx % itemsPerRow === 0 && idx > 0) rows.push([]);
rows[rows.length-1].push(item);
return rows;
}, [[]]);
}
render() {
let rows = this.buildRows(this.props.data, this.props.itemsPerRow);
return (
<ListView
{ ...this.props }
dataSource = { this.state.data.cloneWithRows(rows) }
renderRow = { this.renderRow.bind(this) }
style = {{ flex: 1 }} />
);
}
renderRow(items) {
// Calculate the width of a single item based on the device width
// and the desired margins between individual items
let deviceWidth = Dimensions.get('window').width;
let itemsPerRow = this.props.itemsPerRow;
let margin = this.props.itemMargin || 1;
let totalMargin = margin * (itemsPerRow - 1);
let itemWidth = Math.floor( (deviceWidth - totalMargin) / itemsPerRow );
let adjustedMargin = ( deviceWidth - (itemsPerRow*itemWidth) ) / (itemsPerRow - 1);
return (
<View style = {[ styles.row, { marginBottom: adjustedMargin } ]}>
{ items.map(item => this.props.renderItem(item, itemWidth)) }
</View>
);
}
}
export default PhotoGrid;