Created
May 12, 2020 13:36
-
-
Save johndavedecano/862f4d21117a1201a24ddc7ae87eca1c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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