KatInterview

Build a Collapsible JSON Tree Renderer in React

Trees & GraphsModel answer
MediumModel answerTrees & GraphsReactJSONTree

Last updated

Design and implement a React component to display nested JSON with collapsible nodes, indentation, and syntax highlighting for primitive types.

You are asked to design a React component named JSONViewer that receives a valid parsed JSON value (objects, arrays, strings, numbers, booleans, or null) and renders it as an interactive, styled tree view reminiscent of a code editor.

Requirements

  1. Collapsible Nodes: Complex structures (Object and Array) must be expandable and collapsible. When collapsed, display an abbreviated preview (e.g., {...} or [...] or showing the item count like { 3 keys }).
  2. Indentation: Deeply nested values should be visually indented to convey structure.
  3. Syntax Highlighting: Primitive values (strings, numbers, booleans, null) should be clearly distinguishable using distinct CSS classes or styles based on their data types.
  4. Safety & Security: Render strings safely to prevent cross-site scripting (XSS) or accidental code execution.
  5. Handling Empty Containers: Empty objects {} and empty arrays [] should display gracefully without rendering collapse toggles.

Example Visual Target

{
  ▼ "user": {
      "id": 101,
      "name": "Alice",
      "isAdmin": true,
      ▶ "roles": [ 3 items ]
    },
  "status": null
}

Write the React implementation in modern standard JavaScript/TypeScript using functional components and hooks. Explain how state management works for toggling nested nodes and how performance can be maintained for larger payloads.