Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 73 74 75 76 77 | 9x 25x 25x 8x 17x 17x 25x 2x 6x 6x 12x 14x 2x | import React, { ReactNode } from "react";
import {
ScrollView,
ScrollViewProps,
View,
StyleProp,
ViewStyle,
StyleSheet
} from "react-native";
export interface RNMasonryScrollViewProps extends ScrollViewProps {
children: ReactNode[];
columns?: number;
columnStyle?: StyleProp<ViewStyle>;
oddColumnStyle?: StyleProp<ViewStyle>;
evenColumnStyle?: StyleProp<ViewStyle>;
}
export function generateMasonryGrid<T>(data: T[], columns: number): T[][] {
return data.reduce((collection: T[][], child: T, childIndex: number) => {
const itemIndex = childIndex % columns;
if (collection[itemIndex]) {
collection[itemIndex].push(child);
} else {
collection[itemIndex] = [];
collection[itemIndex].push(child);
}
return collection;
}, []);
}
const RNMasonryScrollView = ({
children = [],
columns = 2,
columnStyle = null,
oddColumnStyle = null,
evenColumnStyle = null,
horizontal,
...otherProps
}: RNMasonryScrollViewProps) => {
const masonryGrid = generateMasonryGrid(children, columns);
return (
<ScrollView
contentContainerStyle={
horizontal ? styles.horizontalColumnStyle : styles.verticalColumnStyle
}
horizontal={horizontal}
{...otherProps}
>
{masonryGrid.map((column, columnIndex) => {
return (
<View
key={columnIndex}
style={[
!horizontal
? styles.horizontalColumnStyle
: styles.verticalColumnStyle,
columnStyle,
columnIndex % 2 === 0 ? evenColumnStyle : oddColumnStyle
]}
>
{column.map(item => item)}
</View>
);
})}
</ScrollView>
);
};
const styles = StyleSheet.create({
verticalColumnStyle: { flexDirection: "row" },
horizontalColumnStyle: { flexDirection: "column" }
});
export default RNMasonryScrollView;
|