@textea/json-viewer

repository·main·Indexed 19 days ago

https://github.com/texteainc/json-viewer

A highly customizable React component for viewing and displaying JSON, Objects, Arrays, Maps, and Sets. It supports SSR, theming (including Base 16 colorspaces), and allows for the creation of custom data types via defineDataType and defineEasyType to render specific structures like images or URL objects. The library is built on Material-UI and Emotion.

Tokens
12.3K
Snippets
39
Records
57
Agent score
67%

What's inside @textea/json-viewer

  1. Optimize performance for large JSON datasets

    main

    When rendering very large objects or arrays, use these props to prevent performance degradation:

    • defaultInspectDepth: Sets the default depth for nested objects to expand. Setting this too high can cause performance issues. (Default: 5)
    • defaultInspectControl: A function (path, currentValue) => boolean that determines whether a field is expanded or collapsed by default. This overrides defaultInspectDepth.
    • maxDisplayLength: Limits the number of items displayed in Array and Object before hiding them. (Default: 30)
    • groupArraysAfterLength: Groups array elements into a collapsible bracket notation after reaching this count. (Default: 100)
    • collapseStringsAfterLength: Truncates strings after this length and adds an ellipsis. Collapsed strings can be expanded by clicking them. (Default: 50)
  2. Migrate from @textea/json-viewer v3 to v4

    main

    To upgrade to version 4, update @textea/json-viewer and @mui/material to their respective major versions. Note that @mui/material version 6 is a required peer dependency for this version of the viewer.

    Important Compatibility Notes:

    • Browser Support: Version 4 no longer supports IE 11 due to the underlying Material-UI 6 dependency. If IE 11 support is required, you must remain on v3.
    • TypeScript: The minimum supported TypeScript version has increased from v3.5 to v4.7.
    • API Change: The createDataType function has been removed. You must replace all usages with defineDataType.
    npm install @textea/json-viewer@^4.0.0
    npm install @mui/material@^6.0.0
  3. Customize JsonViewer appearance with style, className, and sx props

    main

    You can apply basic styling to the JsonViewer component using standard React styling props. This allows you to set inline styles, apply CSS classes, or use the MUI sx prop for advanced styling.

    <JsonViewer style={{ backgroundColor: 'red' }} className="custom-class" sx={{ backgroundColor: 'red' }} />
  4. Use @textea/json-viewer via CDN

    main

    You can use the viewer in a plain HTML environment by loading the script from JSDelivr. You must instantiate JsonViewer with a value object and call .render(selector) to attach it to a DOM element.

    <!doctype html>
    <html lang="en">
      <body>
        <div id="json-viewer"></div
        <script src="https://cdn.jsdelivr.net/npm/@textea/json-viewer@3"></script>
        <script>
          new JsonViewer({
            value: {
              /* ... */
            }
          }).render('#json-viewer')
        </script>
      </body>
    </html>
  5. Install @textea/json-viewer via npm

    main

    To use @textea/json-viewer in a React project, you must install the package along with its peer dependencies, which include Material-UI and Emotion. This is required because the component uses Material-UI as its base library.

    npm install @textea/json-viewer @mui/material @emotion/react @emotion/styled
  6. Migrate from v2 to v3

    main

    To upgrade @textea/json-viewer from version 2 to version 3, you must update the package version and manually install its new peer dependencies. Starting from v3, Material-UI and Emotion are no longer included as direct dependencies and must be provided by the consumer.

    1. Update the package

    npm install @textea/json-viewer@^3.0.0

    2. Install peer dependencies

    Install @mui/material, @emotion/react, and @emotion/styled to satisfy the new dependency requirements:

    npm install @mui/material @emotion/react @emotion/styled

    3. Note on Browser Compatibility

    Version 3 no longer supports ES5 by default. Browser compatibility now follows the Material-UI supported platforms.

    npm install @textea/json-viewer@^3.0.0
    npm install @mui/material @emotion/react @emotion/styled
  7. Migrate from react-json-view to @textea/json-viewer

    main

    If you are moving from mac-s-g/react-json-view, note the following prop mapping:

    react-json-view prop@textea/json-viewer propNote
    namerootName
    srcvalue
    collapseddefaultInspectDepthSet defaultInspectDepth={0} to collapse all.
  8. Install @textea/json-viewer

    main

    To use @textea/json-viewer, you must install it along with its peer dependencies, as it is built on top of Material-UI.

    Install using your preferred package manager:

    npm install @textea/json-viewer @mui/material @emotion/react @emotion/styled
    # or
    yarn add @textea/json-viewer @mui/material @emotion/react @emotion/styled
    # or
    pnpm add @textea/json-viewer @mui/material @emotion/react @emotion/styled
  9. Configure the JsonViewer theme

    main

    Use the theme prop to control the color mode of the JsonViewer.

    Available values:

    • light: Light mode.
    • dark: Dark mode.
    • auto: Automatically switches based on the user's system theme.
    • A custom theme object (such as a Base 16 colorspace).

    When a theme is applied, the following classes are bound to the component root, which you can use for CSS targeting:

    • json-viewer-theme-light
    • json-viewer-theme-dark
    • json-viewer-theme-custom (applied when a custom theme object is passed)
    <JsonViewer
      theme={theme} // 'light', 'dark' or 'auto'
    />
  10. How Function data types are rendered

    main

    When the @textea/json-viewer encounters a Function value in a JSON structure, it uses a specialized functionType renderer.

    Key behaviors:

    • Labeling: It displays a function type label.
    • Name & Braces: It extracts and displays the function name followed by an opening brace {.
    • Inspection Mode:
      • By default, the function body is collapsed and shown as to save space. Clicking the icon triggers inspect mode.
      • When inspect is active, the full string representation of the function body is rendered.
    • SSR Safety: The component uses <NoSsr> to prevent hydration mismatches in frameworks like Next.js, as function stringification can vary between server and client environments.
  11. Define custom DataType for specialized rendering

    main

    You can extend the viewer's capabilities by providing custom DataType definitions via the valueTypes prop. This allows you to control how specific types of data are identified, serialized, and edited.

    Each DataType<ValueType> object requires an is function and a Component for rendering. You can optionally provide an Editor for custom editing logic.

    DataType Interface

    export type DataType<ValueType = unknown> = {
      /** Determines if a value belongs to this type */
      is: (value: unknown, path: Path) => boolean;
      /** Convert value to string for editing */
      serialize?: (value: ValueType) => string;
      /** Convert string back to ValueType (throws on error) */
      deserialize?: (value: string) => ValueType;
      /** Component to render the value */
      Component: ComponentType<DataItemProps<ValueType>>;
      /** Optional custom editor component */
      Editor?: ComponentType<EditorProps<string>>;
      /** Optional component to render before the value */
      PreComponent?: ComponentType<DataItemProps<ValueType>>;
      /** Optional component to render after the value */
      PostComponent?: ComponentType<DataItemProps<ValueType>>;
    }
  12. Register custom data types with TypeRegistryProvider

    main

    To extend the JSON viewer with custom data type rendering, you must use the TypeRegistryProvider and the registerTypes method from the createTypeRegistryStore.

    1. Create a store using createTypeRegistryStore().
    2. Wrap your application (or the JSON viewer component) with TypeRegistryProvider using the created store.
    3. Use registerTypes to update the registry with your custom DataType objects. The registry is initialized with predefinedTypes (boolean, date, null, undefined, string, function, nan, int, float, bigInt).
    import { createTypeRegistryStore, TypeRegistryProvider, useTypeRegistryStore } from '@textea/json-viewer';
    
    // 1. Create the store
    const store = createTypeRegistryStore();
    
    // 2. Wrap your app
    function App() {
      return (
        <TypeRegistryProvider value={store}>
          <MyJsonViewer />
        </TypeRegistryProvider>
      );
    }
    
    // 3. Register custom types later
    function registerMyType() {
      const registryStore = useTypeRegistryStore(state => state);
      registryStore.getState().registerTypes((prevRegistry) => [
        ...prevRegistry,
        myCustomDataType
      ]);
    }