Skip to content

Instantly share code, notes, and snippets.

@sebinsua
Last active March 2, 2021 22:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sebinsua/bad7d57b29c85a436d013868d90902f2 to your computer and use it in GitHub Desktop.
Save sebinsua/bad7d57b29c85a436d013868d90902f2 to your computer and use it in GitHub Desktop.
Basic JSON Viewer
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} />;
}
@sebinsua
Copy link
Author

sebinsua commented Mar 2, 2021

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment