Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save johndavedecano/862f4d21117a1201a24ddc7ae87eca1c to your computer and use it in GitHub Desktop.
Save johndavedecano/862f4d21117a1201a24ddc7ae87eca1c to your computer and use it in GitHub Desktop.
import React from 'react'
import GridLayout from 'react-grid-layout'
import useStateWithCallback from 'use-state-with-callback'
function getLayout() {
try {
return JSON.parse(localStorage.getItem('layout'))
} catch (err) {
return [
{ i: 'a', x: 0, y: 0, w: 1, h: 2, static: true },
{ i: 'b', x: 1, y: 0, w: 3, h: 2, minW: 2, maxW: 4 },
{ i: 'c', x: 4, y: 0, w: 1, h: 2 },
]
}
}
function getPanels() {
try {
return JSON.parse(localStorage.getItem('panels'))
} catch (err) {
return [1, 2, 3, 4, 5]
}
}
function Dashboard() {
const settings = {
cols: 12,
rowHeight: 30,
width: 1200,
}
const [panels, setPanels] = useStateWithCallback(getPanels(), (newPanels) => {
// api request and save to local storage
localStorage.setItem('panels', newPanels)
})
const [layout, setLayout] = useStateWithCallback(getLayout(), (newLayout) => {
// api request and save to local storage
localStorage.setItem('layout', newLayout)
})
const handleLayoutChange = (layout) => setLayout(layout)
const addPanel = () => setPanels(panels.concat([panels.length]))
const removePanel = (key) => () => {
setPanels(panels.filter((k) => k !== key))
}
return (
<GridLayout
className="layout"
layout={layout}
cols={settings.cols}
rowHeight={settings.rowHeight}
width={settings.width}
onLayoutChange={handleLayoutChange}
>
<Button onClick={addPanel}>Add Panel</Button>
{panels.map((key) => (
<div key={key}>
{key}
<Button onClick={removePanel(key)}>Remove Panel</Button>
</div>
))}
</GridLayout>
)
}
export default Dashboard
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment