Skip to content

Instantly share code, notes, and snippets.

@sebinsua
Last active Mar 2, 2021
Embed
What would you like to do?
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