I am using react-grid-layout to create a dashboard with resizable and draggable cards. Each card is a ResponsiveGridLayout item and takes up the size of a single grid unit. I want the cards to have a specific size when the site loads.
Here's a simplified version of my code:
import React, { useState, useMemo} from 'react';
import { Card } from 'react-bootstrap';
import { Responsive, WidthProvider } from 'react-grid-layout';
import _ from 'lodash';
import 'react-grid-layout/css/styles.css';
import 'react-resizable/css/styles.css';
const ResponsiveGridLayout = WidthProvider(Responsive);
const renderCard = (key, header, body) => (
<div key={key}>
<Card bg="dark" text="white" style={{ height: '100%' }}>
<Card.Header>{header}</Card.Header>
<Card.Body onMouseDown={(event) => {
// Stop propagation to prevent drag from starting
event.stopPropagation();
}}>
{body}
</Card.Body>
</Card>
</div>
);
function Dashboard() {
const cards = useMemo(() => [
{ id: "1", header: 'Hello There', body: <Card.Text>XXX</Card.Text> },
{ id: "2", header: 'General Kenobi', body: <Card.Text>What.up</Card.Text> },
], []);
function generateLayout() {
return _.map(cards, function(card, i) {
const y = Math.ceil(Math.random() * 4) + 1;
return {
x: (i * 2) % 12,
y: Math.floor(i / 6) * y,
w: 100,
h: y,
i: card.id,
};
});
}
const [layout] = useState(() => {
const savedLayout = localStorage.getItem('layout');
return savedLayout ? JSON.parse(savedLayout) : generateLayout();
});
const colWidth = 1;
const rowHeight = 1;
const calculateCols = () => Math.floor(window.innerWidth / colWidth);
return (
<div>
<ResponsiveGridLayout
className="layout"
layout={layout}
isResizable={true}
cols={{lg: calculateCols(), md: calculateCols(), sm: calculateCols()}}
rowHeight={rowHeight}
compactType={null}
verticalCompact={false}
>
{cards.map(card => renderCard(card.id, card.header, card.body))}
</ResponsiveGridLayout>
</div>
);
}
export default Dashboard;
I want the cards to have a specific size or even better depending on number of items visible and window size.
How can I set a specific initial size for the cards in my react-grid-layout?
I mean there has to be a function for the resizing of the grid-item which should be callable??