Code from blogpost: http://blog.rudikovac.com/react-native-drawer-with-a-variable-number-of-images-in-a-listview-grid/
class Something extends React.Component<{}, {drawerWidth: number, dataSource: any, db: any}> { | |
constructor(props) { | |
super(props) | |
this.state = { | |
drawerWidth: 0, | |
dataSource: new ListView.DataSource({ | |
rowHasChanged: (row1, row2) => row1 !== row2 || this.state.drawerWidth != 0 | |
// drawerWidth changing from 0 will force a row re-render | |
}), | |
db: [] | |
} | |
this.calcWidth = this.calcWidth.bind(this) | |
} | |
calcWidth(e) { | |
let dbCopy = Object.assign({}, this.state.db) | |
let that = this | |
this.setState(Object.assign({}, this.state, { drawerWidth: e.nativeEvent.layout.width }), function() { | |
if (e.nativeEvent.layout.width != 0) { | |
// re-fill dataSource in order to force a re-render | |
// this is needed because in some cases the drawer width is passed as 0 or NaN and will be rendered too soon | |
// https://github.com/facebook/react-native/issues/1133 | |
// http://stackoverflow.com/questions/31738671/react-native-updating-list-view-datasource | |
that.setState(Object.assign({}, that.state, { dataSource: that.state.dataSource.cloneWithRows(dbCopy), db: dbCopy })) | |
} | |
}) | |
} | |
componentDidMount() { | |
let db = require('./db.json') | |
this.setState(Object.assign({}, this.state, { dataSource: this.state.dataSource.cloneWithRows(db), db: db })) | |
} | |
render() { | |
return ( | |
<ScrollView onLayout={this.calcWidth}> | |
<ListView | |
contentContainerStyle={styles.drawerContent as any} // this makes a nice grid | |
dataSource={this.state.dataSource} | |
renderRow={rowData => <OtherStuff rowData={rowData} drawerWidth={this.state.drawerWidth} />} | |
/> | |
</ScrollView> | |
) | |
} | |
} | |
class OtherStuff extends React.Component<{rowData: any, drawerWidth: number}, {}> { | |
calcWidth() { | |
var size = (this.props.drawerWidth / 2) - 20 | |
return { width: size, height: size } | |
} | |
render() { | |
const {rowData} = this.props | |
return ( | |
<View style={[styles.otherStyles, this.calcWidth()]}> | |
<Image source={{ uri: rowData.imageUrl || 'https://something.else/image.jpg' }} resizeMode="cover" style={[{ somethingElse: 5 }, this.calcWidth()]} /> | |
</View> | |
) | |
} | |
} | |
const styles = StyleSheet.create({ | |
drawerContent: { | |
flex: 1, | |
flexWrap: 'wrap', | |
flexDirection: 'row', | |
justifyContent: 'space-between' | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment