CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-react-json-tree

React JSON Viewer Component providing interactive tree visualization for JSON data structures with support for custom themes and complex data types.

Pending
Overview
Eval results
Files

index.mddocs/

React JSON Tree

React JSON Tree is a React component for visualizing JSON data structures in an interactive tree format. It supports collapsible/expandable nodes, custom themes based on base16 color schemes, and advanced JavaScript data types including Immutable.js collections and other iterable objects.

Package Information

  • Package Name: react-json-tree
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install react-json-tree

Core Imports

import { JSONTree } from "react-json-tree";
import type { 
  Key, 
  KeyPath, 
  GetItemString, 
  LabelRenderer, 
  ValueRenderer,
  ShouldExpandNodeInitially,
  PostprocessValue,
  IsCustomNode,
  SortObjectKeys,
  Styling,
  CommonExternalProps,
  StylingValue
} from "react-json-tree";

For CommonJS:

const { JSONTree } = require("react-json-tree");

Basic Usage

import { JSONTree } from "react-json-tree";

const data = {
  array: [1, 2, 3],
  bool: true,
  object: {
    foo: "bar"
  },
  string: "Hello World",
  number: 42,
  null: null
};

function App() {
  return <JSONTree data={data} />;
}

Architecture

React JSON Tree is built around several key components:

  • JSONTree Component: Main component that renders the interactive tree structure
  • Theme System: Base16 theme support with light/dark variants and custom styling capabilities
  • Type Detection: Automatic detection and handling of JavaScript data types including primitives, collections, and iterables
  • Rendering Pipeline: Customizable renderers for labels, values, and collection previews
  • Expansion Control: Configurable node expansion behavior with initial state control

Capabilities

JSONTree Component

The main component for rendering JSON data as an interactive tree.

interface JSONTreeProps extends Partial<CommonExternalProps> {
  /** The JSON data to display */
  data: unknown;
  /** Base16 theme or custom styling configuration */
  theme?: Theme;
  /** Whether to invert the theme colors (light/dark mode toggle) */
  invertTheme?: boolean;
}

function JSONTree(props: JSONTreeProps): React.ReactElement;

Usage Examples:

// Basic usage
<JSONTree data={myData} />

// With theme
<JSONTree 
  data={myData} 
  theme={{
    scheme: 'monokai',
    base00: '#272822',
    base01: '#383830',
    // ... other base16 colors
  }}
/>

// With theme inversion
<JSONTree data={myData} theme={myTheme} invertTheme={true} />

Customization Options

React JSON Tree provides extensive customization through the CommonExternalProps interface.

interface CommonExternalProps {
  /** Path to the root node, defaults to ['root'] */
  keyPath: KeyPath;
  /** Custom function to render property labels */
  labelRenderer: LabelRenderer;
  /** Custom function to render values */
  valueRenderer: ValueRenderer;
  /** Function to determine initial node expansion */
  shouldExpandNodeInitially: ShouldExpandNodeInitially;
  /** Hide the root node wrapper */
  hideRoot: boolean;
  /** Custom function to render collection previews */
  getItemString: GetItemString;
  /** Function to preprocess values before rendering */
  postprocessValue: PostprocessValue;
  /** Function to override default object type detection */
  isCustomNode: IsCustomNode;
  /** Maximum number of items to show before collapsing ranges */
  collectionLimit: number;
  /** Sort object keys (boolean for default sort, function for custom) */
  sortObjectKeys: SortObjectKeys;
}

Custom Label Rendering:

<JSONTree
  data={data}
  labelRenderer={([key]) => <strong style={{color: 'blue'}}>{key}</strong>}
/>

Custom Value Rendering:

<JSONTree
  data={data}
  valueRenderer={(raw, value) => <em>{String(raw)}</em>}
/>

Custom Collection Preview:

<JSONTree
  data={data}
  getItemString={(type, data, itemType, itemString) => (
    <span>// {type} with {itemString}</span>
  )}
/>

Initial Expansion Control:

<JSONTree
  data={data}
  shouldExpandNodeInitially={(keyPath, data, level) => level < 2}
/>

Object Key Sorting:

// Default alphabetical sorting
<JSONTree data={data} sortObjectKeys={true} />

// Custom sorting
<JSONTree 
  data={data} 
  sortObjectKeys={(a, b) => String(a).localeCompare(String(b), undefined, {numeric: true})}
/>

Advanced Customization

/** Theme type from react-base16-styling - can be a Base16Theme or custom styling object */
type Theme = Base16Theme | { [styleName: string]: any };

/** Complete Base16 theme interface */
interface Base16Theme {
  scheme: string;
  author: string;
  base00: string; // Default Background
  base01: string; // Lighter Background
  base02: string; // Selection Background
  base03: string; // Comments, Invisibles
  base04: string; // Dark Foreground
  base05: string; // Default Foreground
  base06: string; // Light Foreground
  base07: string; // Light Background
  base08: string; // Variables, XML Tags
  base09: string; // Integers, Boolean, Constants
  base0A: string; // Classes, Markup Bold
  base0B: string; // Strings, Inherited Class
  base0C: string; // Support, Regular Expressions
  base0D: string; // Functions, Methods, Attribute IDs
  base0E: string; // Keywords, Storage, Selector
  base0F: string; // Deprecated, Opening/Closing Tags
}

/** Custom theme with style overrides */
interface CustomTheme extends Partial<Base16Theme> {
  extend?: Theme;
  [styleName: string]: any;
}

Advanced Theme Customization:

<JSONTree
  data={data}
  theme={{
    extend: baseTheme,
    // Custom styles for specific elements
    valueLabel: {
      textDecoration: 'underline'
    },
    nestedNodeLabel: ({ style }, keyPath, nodeType, expanded) => ({
      style: {
        ...style,
        textTransform: expanded ? 'uppercase' : style.textTransform
      }
    })
  }}
/>

Types

Core Types

/** Type for object keys or array indices */
type Key = string | number;

/** Array representing the path to a nested value */
type KeyPath = readonly (string | number)[];

/** Styling function from react-base16-styling */
type Styling = StylingFunction;

/** Styling value type from react-base16-styling */
type StylingValue = unknown;

Renderer Function Types

/** Function to customize collection preview display */
type GetItemString = (
  nodeType: string,
  data: unknown,
  itemType: React.ReactNode,
  itemString: string,
  keyPath: KeyPath,
) => React.ReactNode;

/** Function to customize property label rendering */
type LabelRenderer = (
  keyPath: KeyPath,
  nodeType: string,
  expanded: boolean,
  expandable: boolean,
) => React.ReactNode;

/** Function to customize value rendering */
type ValueRenderer = (
  valueAsString: unknown,
  value: unknown,
  ...keyPath: KeyPath
) => React.ReactNode;

/** Function to determine initial node expansion */
type ShouldExpandNodeInitially = (
  keyPath: KeyPath,
  data: unknown,
  level: number,
) => boolean;

/** Function to preprocess values before rendering */
type PostprocessValue = (value: unknown) => unknown;

/** Function to override default object type detection */
type IsCustomNode = (value: unknown) => boolean;

/** Sorting function for object keys or boolean for default sorting */
type SortObjectKeys = ((a: unknown, b: unknown) => number) | boolean;

Supported Data Types

React JSON Tree automatically detects and handles all JavaScript data types:

  • Primitives: string, number, boolean, null, undefined
  • Objects: Plain objects, custom class instances
  • Arrays: Regular arrays with numeric indices
  • Functions: Function objects (displayed as [Function])
  • Symbols: Symbol values
  • Dates: Date objects with formatted display
  • Errors: Error objects with message display
  • Collections: Map, Set, WeakMap, WeakSet
  • Iterables: Any object implementing the iterable protocol (including Immutable.js collections)

Theme System

React JSON Tree uses the base16 theming system from react-base16-styling. The Base16Theme interface (defined above in Advanced Customization) provides 16 color slots for consistent theming.

Built-in Default Theme:

The package includes a built-in Solarized theme as the default, providing good contrast and readability. When no theme is provided, this default theme is automatically applied.

Performance Features

  • Collection Limiting: Large arrays and objects are automatically paginated using the collectionLimit prop (default: 50 items)
  • Lazy Expansion: Nodes are only rendered when expanded, improving performance for large datasets
  • Efficient Re-rendering: Uses React's reconciliation to minimize DOM updates
  • Memory Optimization: Circular reference detection prevents infinite loops

Install with Tessl CLI

npx tessl i tessl/npm-react-json-tree

docs

index.md

tile.json