Build a Collapsible JSON Tree Renderer in React
Trees & GraphsModel answerLast 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
- Collapsible Nodes: Complex structures (
ObjectandArray) must be expandable and collapsible. When collapsed, display an abbreviated preview (e.g.,{...}or[...]or showing the item count like{ 3 keys }). - Indentation: Deeply nested values should be visually indented to convey structure.
- Syntax Highlighting: Primitive values (strings, numbers, booleans,
null) should be clearly distinguishable using distinct CSS classes or styles based on their data types. - Safety & Security: Render strings safely to prevent cross-site scripting (XSS) or accidental code execution.
- 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Building an interactive JSON tree viewer requires a recursive component structure. JSON values fall into two main categories:
- Primitives:
string,number,boolean,null. These are terminal nodes (leaves of the tree) and render as highlighted text values based on their type. - Containers:
ObjectandArray. These are non-terminal nodes (branches) that contain key-value pairs or index-element pairs. Containers need interactive toggle capabilities to expand or collapse child elements.
Key Architectural Considerations
- Local State for Expand/Collapse: Storing the open/closed state locally inside each container component (via standard
useState) ensures that toggling a node only re-renders that sub-tree rather than triggering a re-render of the entire tree. - Data Type Identification:
nullis a special case in JavaScript wheretypeof null === 'object'. We must explicitly guard againstnullbefore checking if a target is a complex object. - XSS Prevention: React automatically escapes text rendered within JSX children, protecting against basic HTML injection. Extra care is only required if custom HTML injection like
dangerouslySetInnerHTMLis used (which we avoid here).
React Component Implementation
import React, { useState } from 'react';
// Primitive value component with syntax highlighting
const JSONPrimitive = ({ value }) => {
if (value === null) {
return <span style={{ color: '#888', fontStyle: 'italic' }}>null</span>;
}
const type = typeof value;
if (type === 'string') {
return <span style={{ color: '#ce9178' }}>"{value}"</span>;
}
if (type === 'number') {
return <span style={{ color: '#b5cea8' }}>{value}</span>;
}
if (type === 'boolean') {
return <span style={{ color: '#569cd6' }}>{String(value)}</span>;
}
return <span>{String(value)}</span>;
};
// Main Recursive Node Renderer
const JSONNode = ({ keyName, value, depth = 0 }) => {
const [isExpanded, setIsExpanded] = useState(true);
const isNull = value === null;
const isArray = Array.isArray(value);
const isObject = typeof value === 'object' && !isNull && !isArray;
const isContainer = isObject || isArray;
// Handle Primitive Types
if (!isContainer) {
return (
<div style={{ paddingLeft: `${depth * 16}px`, fontFamily: 'monospace', lineHeight: '1.5' }}>
{keyName !== undefined && <span style={{ color: '#9cdcfe' }}>"{keyName}": </span>}
<JSONPrimitive value={value} />
</div>
);
}
// Handle Containers (Objects and Arrays)
const keys = isObject ? Object.keys(value) : value.map((_, i) => i);
const isEmpty = keys.length === 0;
const openBrace = isArray ? '[' : '{';
const closeBrace = isArray ? ']' : '}';
// Render empty object/array
if (isEmpty) {
return (
<div style={{ paddingLeft: `${depth * 16}px`, fontFamily: 'monospace', lineHeight: '1.5' }}>
{keyName !== undefined && <span style={{ color: '#9cdcfe' }}>"{keyName}": </span>}
<span>{openBrace}{closeBrace}</span>
</div>
);
}
return (
<div style={{ fontFamily: 'monospace', lineHeight: '1.5' }}>
<div
style={{ paddingLeft: `${depth * 16}px`, cursor: 'pointer', userSelect: 'none' }}
onClick={() => setIsExpanded(!isExpanded)}
>
<span style={{ color: '#888', marginRight: '6px' }}>
{isExpanded ? '▼' : '▶'}
</span>
{keyName !== undefined && <span style={{ color: '#9cdcfe' }}>"{keyName}": </span>}
<span>{openBrace}</span>
{!isExpanded && (
<span style={{ color: '#888', fontStyle: 'italic' }}>
{` ... ${keys.length} ${keys.length === 1 ? 'item' : 'items'} ${closeBrace}`}
</span>
)}
</div>
{isExpanded && (
<div>
{keys.map((key) => (
<JSONNode
key={key}
keyName={isObject ? key : undefined}
value={value[key]}
depth={depth + 1}
/>
))}
<div style={{ paddingLeft: `${depth * 16}px` }}>
{closeBrace}
</div>
</div>
)}
</div>
);
};
// Root Component Wrapper
export default function JSONViewer({ data }) {
return (
<div style={{ backgroundColor: '#1e1e1e', color: '#d4d4d4', padding: '16px', borderRadius: '8px' }}>
<JSONNode value={data} />
</div>
);
}
Key Design Trade-offs & Performance Considerations
-
Local State vs. Lifted State:
- Local State (
useStateper container): Toggling expand/collapse is cheap because React only re-renders the component managing that node and its children. However, state resets if the inputdataobject reference changes completely. - Lifted State (Global path map): Tracking expanded paths centrally (e.g.,
Set<string>containing path strings like'user.roles[0]') allows preserving expand state across payload updates, but requires prop drilling or context, and re-renders more of the tree on each toggle.
- Local State (
-
Large Datasets & Virtualization:
- For deeply nested or massive JSON objects (10,000+ nodes), DOM element creation becomes a bottleneck.
- A production-grade implementation would flatten visible nodes into a single array view when expanded and use dynamic windowing/virtualization (e.g.,
react-window) to render only visible lines on screen.