Skip to content

Instantly share code, notes, and snippets.

@EvanMarie
Created September 10, 2024 18:12
Show Gist options
  • Save EvanMarie/4fe6fd3dd083354f972141441da80e42 to your computer and use it in GitHub Desktop.
Save EvanMarie/4fe6fd3dd083354f972141441da80e42 to your computer and use it in GitHub Desktop.
export function RenderJSONExample({
JSONString,
scrollRef,
}: {
JSONString: string;
scrollRef: React.RefObject<HTMLDivElement>;
}) {
try {
// Parse the input JSON string
const shape = JSON.parse(JSONString);
// Recursive function to render nested objects and arrays
const renderValue = (value: any, isChild = false) => {
if (Array.isArray(value)) {
return value.map((item, index) => (
<VStackFull
align="items-start"
key={index}
className={`${
isChild
? "pl-2vh"
: "border-600-md p-[1.5vh] rounded-[2vh] shadowNarrowNormal bg-col-900 bg-gradient-to-br from-indigo-800/30 via-sky-900/30 to-indigo-800/30"
} w-full h-full `}
gap="gap-0"
>
{renderValue(item, true)} {/* Recursively render arrays */}
</VStackFull>
));
} else if (typeof value === "object" && value !== null) {
return Object.keys(value).map((subKey) => (
<VStackFull
key={subKey}
className={`${isChild ? "pl-2vh" : ""} w-full h-full`}
align="items-start"
gap="gap-0"
>
<HStackFull className="">
<Text className="text-cyan-300 text-sm textShadow">
<strong>{subKey}:</strong>
</Text>
<VStackFull className="w-full " align="items-start">
{renderValue(value[subKey], true)}{" "}
{/* Recursively render objects */}
</VStackFull>
</HStackFull>
</VStackFull>
));
} else {
// Render primitive values as text
return (
<Text className="text-sm text-col-100 text-stroke-5-100">
{String(value)}
</Text>
);
}
};
return (
// Main container with scroll progress
<Transition
className="w-[98vw] md:w-[80vh] bg-col-700 insetShadow3xl h-[56vh] overflow-y-auto overflow-x-hidden p-[1vh]"
ref={scrollRef}
>
<VStackFull
className="w-full h-fit p-[1vh]"
gap="gap-0"
align="items-start"
>
{Object.keys(shape).map((key, index) => (
<VStackFull key={index} className="w-full h-full" gap="gap-0">
{/* Top-level key */}
<Text className="text-[4vh] text-cyan-300 text-semibold textShadow">
{key}
</Text>
<VStackFull className="w-full" gap="gap-0" align="items-start">
{renderValue(shape[key])}
</VStackFull>
</VStackFull>
))}
</VStackFull>
</Transition>
);
} catch (error: any) {
return (
<Text className="text-red-500">
Invalid JSON or unsupported structure: {error.message}
</Text>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment