react-json-view-lite

repository·release·Indexed 42 days ago

https://github.com/anyroad/react-json-view-lite

A lightweight, dependency-free React component for rendering JSON data as an interactive tree. Focused on performance for large volume input, it supports collapsing/expanding nodes, custom styling via StyleProps, and accessibility features. Version 2.5.0 requires React 18 or later.

Tokens
3.4K
Snippets
9
Records
16
Agent score
4%

What's inside react-json-view-lite

  1. Compare performance and size

    release

    Size Comparison

    react-json-view-lite is designed to be lightweight compared to other popular React JSON viewers like react-json-inspector or react-json-view.

    Performance

    Performance was measured using react-component-benchmark with a 300Kb JSON file. While react-json-pretty is faster, it lacks the ability to collapse/expand nested objects. react-json-view-lite provides a balance of performance and interactive features.

    LibraryAverage Render (ms)Median Render (ms)
    react-json-view-lite19582
    react-json-pretty3224
    react-json-inspector758711
    react-json-tree658620
    react-json-view15291540
    react-json-tree-viewer320278
  2. Compatibility and Version 2.x.x requirements

    release

    React Version Compatibility

    • Version 2.x.x: Requires React 18 or later.
    • Version 1.5.0: Use this version if your project uses React 16 or 17.

    Version 2 Improvements

    • Better accessibility (a11y) support.
    • Improved navigation through nested elements using arrow keys.
    • Note: The Space button no longer collapses/expands elements in v2.
    • Library size has increased by approximately 20% compared to v1.

    Custom Styling in v2

    Because the implementation uses a div instead of a ul for the childFieldsContainer (following W3C treeview patterns), you may need to reset margins/padding in your CSS:

    .child-fields-container {
      margin: 0;
      padding: 0;
    }
  3. Migrate from 0.9.x to 2.x.x

    release

    If you are upgrading from version 0.9.x, note the following breaking changes:

    1. Prop Renaming: shouldInitiallyExpand is now shouldExpandNode. This change emphasizes that the function is called every time properties change.
    2. Custom Styling Changes:
      • pointer and expander props are no longer used.
      • To customize expand/collapse icons and collapsed content placeholders (previously hardcoded to ▸, ▾, and ...), use the collapseIcon, expandIcon, and collapsedContent styles. These use ::after pseudo-classes to set content.
  4. Quickstart usage of JsonView

    release

    To use react-json-view-lite, import the JsonView component and its associated CSS. You can use built-in styles like defaultStyles or darkStyles.

    Important: If you pass a function to shouldExpandNode, wrap it in a useCallback or define it outside your component to prevent unnecessary re-renders, as anonymous functions are recreated on every render.

    import * as React from 'react';
    
    import { JsonView, allExpanded, darkStyles, defaultStyles } from 'react-json-view-lite';
    import 'react-json-view-lite/dist/index.css';
    
    const json = {
      a: 1,
      b: 'example'
    };
    
    const App = () => {
      return (
        <React.Fragment>
          <JsonView data={json} shouldExpandNode={allExpanded} style={defaultStyles} />
          <JsonView data={json} shouldExpandNode={allExpanded} style={darkStyles} />
        </React.Fragment>
      );
    };
    
    export default App;
  5. Use the beforeExpandChange callback

    release
    The beforeExpandChange prop allows you to intercept expansion/collapse events. It receives a NodeExpandingEvent object. If the callback returns false, the node state remains unchanged. This is useful for controlling which children nodes are allowed to open.
  6. Configure JsonView props

    release

    The JsonView component accepts several props to control the rendering of the JSON tree:

    • data: The Object or Array to be rendered.
    • style: StyleProps for CSS classes. Defaults to defaultStyles. Built-in options include darkStyles and defaultStyles.
    • shouldExpandNode: A function (level: number, value: any, field?: string) => boolean called during initial rendering and whenever properties change to determine if a node should be expanded. Defaults to allExpanded. Built-in options include allExpanded and collapseAllNested.
    • clickToExpandNode: boolean. If true, clicking the node itself expands/collapses it. Defaults to false.
    • beforeExpandChange: A function (event: NodeExpandingEvent) => boolean called before a node expands or collapses. Returning false cancels the action.
    • compactTopLevel: boolean. If true, hides the top-level collapse/expand button and indentation (only works if data is an Object). Defaults to false.
  7. Reference the NodeExpandingEvent interface

    release

    The NodeExpandingEvent object contains the following fields:

    Field NameTypeDescription
    levelnumberlevel of expanded/collapsed node
    valueanyField value (object or array) to be expanded/collapsed
    fieldstring?Field name
    newExpandValuebooleanif node is about to be expanded (true) or collapsed (false)
  8. Configure accessibility with AriaLabels

    release

    Use the ariaLables prop to provide custom aria-label text for the interactive buttons in the JSON viewer, improving accessibility for screen readers.

    Field NameTypeDescription
    collapseJsonstringaria-label for the "collapse" node button. Default: "collapse JSON"
    expandJsonstringaria-label for the "expand" node button. Default: "expand JSON"
  9. Customize appearance with StyleProps

    release

    The StyleProps interface allows you to customize the CSS classes and rendering behavior of the JSON viewer. You can control the class names for every part of the tree (containers, labels, values) and toggle specific rendering features like quotes or stringification.

    NameTypeDescription
    containerstringCSS class for the parent block
    childFieldsContainerstringCSS class for the parent block of an array or object
    basicChildStylestringCSS class for the property block (name + value)
    collapseIconstringCSS class for the collapse button. Default content: ▾
    expandIconstringCSS class for the expand button. Default content: ▸
    collapsedContentstringCSS class for the placeholder when nodes are collapsed. Default content: ...
    labelstringCSS class for property names
    clickableLabelstringCSS class for clickable property names (requires clickToExpandNode: true)
    nullValuestringCSS class for null values
    undefinedValuestringCSS class for undefined values
    numberValuestringCSS class for numeric values
    stringValuestringCSS class for string values
    booleanValuestringCSS class for boolean values
    otherValuestringCSS class for all other types
    punctuationstringCSS class for ,, [, ], {, }
    noQuotesForStringValuesbooleanIf true, removes double quotes from strings. Default: false
    quotesForFieldNamesbooleanIf true, adds double quotes to field names. Default: false
    ariaLablesAriaLabelsObject to customize accessibility labels
    stringifyStringValuesbooleanIf true, uses JSON.stringify for strings to preserve escaped characters (e.g., \n, \t).
  10. Use exported utility functions and styles

    release

    The library exports several utilities for managing expansion states and pre-defined styles:

    Styles

    • defaultStyles: StyleProps object for light backgrounds.
    • darkStyles: StyleProps object for dark backgrounds.

    Expansion Logic

    • allExpanded: A function () => boolean that always returns true (useful for forcing all nodes to be open).
    • collapseAllNested: A function (level: number) => boolean that returns true only for the first level (level=0).
    import { defaultStyles, darkStyles, allExpanded, collapseAllNested } from 'react-json-view-lite';
  11. Configure JsonView expansion behavior

    release

    You can control which nodes are expanded by default or intercept expansion events using shouldExpandNode and beforeExpandChange.

    Default Expansion Helpers

    • allExpanded: A helper function that returns true for all nodes.
    • collapseAllNested(level: number): A helper function that returns true only for nodes at a level less than the specified value (useful for collapsing everything below a certain depth).

    Intercepting Expansion

    The beforeExpandChange prop receives a NodeExpandingEvent object. If the callback returns false, the expansion/collapse action is cancelled.

    NodeExpandingEvent properties:

    • level: The depth of the node.
    • value: The value of the node.
    • field: The key/field name (optional).
    • newExpandValue: The new expansion state (boolean).
    import { JsonView, allExpanded, collapseAllNested } from 'react-json-view-lite';
    
    // Example: Only expand nodes at level 0 and 1
    const shouldExpand = (level: number) => level < 2;
    
    // Example: Prevent collapsing if it's a specific field
    const handleBeforeExpand = (event: NodeExpandingEvent) => {
      if (event.field === 'protected_field' && !event.newExpandValue) {
        return false; // Prevent collapsing
      }
      return true;
    };
    
    <JsonView 
      data={myData} 
      shouldExpandNode={shouldExpand} 
      beforeExpandChange={handleBeforeExpand} 
    />