Last active
March 2, 2021 22:40
-
-
Save sebinsua/bad7d57b29c85a436d013868d90902f2 to your computer and use it in GitHub Desktop.
Basic JSON Viewer
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 { useCallback, useState } from "react"; | |
const MAXIMUM_DEPTH = 1; | |
function Node({ | |
value, | |
depth = 1, | |
isExpandedDefault = depth <= MAXIMUM_DEPTH | |
}) { | |
const [isExpanded, setIsExpanded] = useState(isExpandedDefault); | |
const toggle = useCallback(() => setIsExpanded((v) => !v), []); | |
if (Array.isArray(value)) { | |
return ( | |
<> | |
<div> | |
<button onClick={toggle}>{isExpanded ? "-" : "+"}</button> | |
</div> | |
<ul style={{ display: isExpanded === false ? "none" : undefined }}> | |
{value.map((v, k) => ( | |
<li key={k}> | |
<Node value={v} depth={depth} isExpandedDefault /> | |
</li> | |
))} | |
</ul> | |
</> | |
); | |
} else if (typeof value === "object" && value !== null) { | |
return ( | |
<> | |
<div> | |
<button onClick={toggle}>{isExpanded ? "-" : "+"}</button> | |
</div> | |
<ul style={{ display: isExpanded === false ? "none" : undefined }}> | |
{Object.entries(value).map(([k, v]) => ( | |
<li key={k}> | |
<span> | |
{k} ({depth}) | |
</span> | |
: <Node value={v} depth={depth + 1} /> | |
</li> | |
))} | |
</ul> | |
</> | |
); | |
} | |
return <span>{value}</span>; | |
} | |
const tree = { | |
hello: "world", | |
items: [ | |
{ | |
value: 1 | |
}, | |
{ | |
value: 2, | |
deep: { | |
name: "wow" | |
} | |
}, | |
{ | |
value: 3 | |
} | |
] | |
}; | |
export default function App() { | |
return <Node value={tree} />; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See: https://codesandbox.io/s/strange-proskuriakova-yj4rs?file=/src/App.js