I’m looking at the react-grid-layout which is based on Material Design’s 12 column grid. Is there a way to provide pre-defined sizes for containers to stick to the following 3 sizes: 1 full width (12 cols), half grid (6 cols) or 1/3 grid (4 cols)?
Advertisement
Answer
My guess is that when you say container, you’re referring to the layout items. If that is the case, use a custom onResize
method. Using the sandbox code you have from your question:
JavaScript
x
67
67
1
export default class ShowcaseLayout extends React.Component {
2
constructor(props) {
3
4
// add the line below
5
this.onResize = this.onResize.bind(this);
6
}
7
8
9
10
// add the method
11
onResize(layout, oldLayoutItem, layoutItem, placeholder) {
12
// `oldLayoutItem` contains the state of the item before the resize.
13
// You can modify `layoutItem` to enforce constraints.
14
const allowableW = this.props.cols[this.state.currentBreakpoint] - oldLayoutItem.x
15
if (layoutItem.w <= 4) {
16
layoutItem.w = 4;
17
placeholder.w = 4;
18
} else if (layoutItem.w <= 6) {
19
layoutItem.w = allowableW < 6 ? 4 : 6;
20
placeholder.w = allowableW < 6 ? 4 : 6;
21
} else {
22
layoutItem.w = allowableW < 12 ? 6 : 12;
23
placeholder.w = allowableW < 12 ? 6 : 12;
24
}
25
}
26
27
render() {
28
return (
29
<div>
30
31
<ResponsiveReactGridLayout
32
33
{/* bind method to component */}
34
onResize={this.onResize}
35
>
36
{this.generateDOM()}
37
</ResponsiveReactGridLayout>
38
</div>
39
);
40
}
41
}
42
43
ShowcaseLayout.propTypes = {
44
onLayoutChange: PropTypes.func.isRequired
45
};
46
47
ShowcaseLayout.defaultProps = {
48
49
// ensure your breakpoints have a minimum of 4 columns
50
cols: { lg: 12, md: 10, sm: 6, xs: 4, xxs: 4 },
51
};
52
53
function generateLayout() {
54
return _.map(_.range(0, 25), function (item, i) {
55
var y = Math.ceil(Math.random() * 4) + 1;
56
return {
57
x: (_.random(0, 5) * 2) % 12,
58
y: Math.floor(i / 6) * y,
59
// set item's default width to 4
60
w: 4,
61
h: y,
62
i: i.toString(),
63
static: Math.random() < 0.05
64
};
65
});
66
}
67