@uiw/react-json-view

repository·main·Indexed 19 days ago

https://github.com/uiwjs/react-json-view

A React component library for displaying and editing JavaScript arrays and JSON objects. It features customizable themes, TypeScript support, and zero dependencies. The library provides the primary JsonView component for interactive trees, JsonViewEditor for editable data, and a Provider for global configuration of indentation, sorting, and display behavior.

Tokens
6.5K
Snippets
19
Records
30
Agent score
65%

What's inside @uiw/react-json-view

  1. Customize section elements with Section and useSectionStore

    main

    The Section component and useSectionStore hook allow you to provide custom configuration for the visual elements used within the JSON viewer (such as the ellipsis, key names, and row containers).

    By wrapping your component tree in a Section provider, you can override the default styles and HTML tags for internal UI elements. You can then access these configurations using the useSectionStore hook.

    Available Section Elements

    When providing an initial state to the Section component, you can customize the following keys:

    • Copied: The element shown when a value is copied.
    • CountInfo: The element displaying object size/info.
    • CountInfoExtra: Additional info element.
    • Ellipsis: The element used for truncated objects (e.g., ...).
    • Row: The container for a single JSON line/row.
    • KeyName: The element used to render object keys.
    import { Section, useSectionStore } from './path-to-section';
    
    const customInitial = {
      Ellipsis: {
        as: 'span',
        style: { color: 'red' },
        children: ' (more)'
      },
      // ... other elements
    };
    
    function App() {
      return (
        <Section initial={customInitial} dispatch={dispatch}>
          <MyJsonViewer />
        </Section>
      );
    }
    
    // Inside a child component:
    function MyJsonViewer() {
      const section = useSectionStore();
      // section.Ellipsis contains your custom config
    }
  2. Control initial node expansion

    main

    You can control which nodes are expanded when the component first mounts using either collapsed or shouldExpandNodeInitially.

    1. Using collapsed:

      • Set to true to collapse all nodes.
      • Set to a number (e.g., 2) to collapse all nodes deeper than that specific depth.
      • Note: collapsed takes precedence over shouldExpandNodeInitially.
    2. Using shouldExpandNodeInitially: Provide a function to implement custom logic for expansion based on the node's properties.

    type ShouldExpandNodeInitially<T extends object> = (
      isExpanded: boolean,
      props: { keyName?: string | number; value?: T; parentValue?: T; keys: (number | string)[]; level: number },
    ) => boolean;
  3. Customize type rendering using the render prop pattern

    main

    Each type component (e.g., TypeString, TypeInt, TypeUrl) can be customized by providing a render function through the useTypesStore. The render function is called twice: once for the 'type' (the label/metadata) and once for the 'value' (the actual data).

    Render function arguments:

    1. props: An object containing configuration like as (the HTML element to use), style, className, and children.
    2. context: An object containing { type: 'type' | 'value', value, keyName, keys }.
  4. Configure data type rendering with InitialTypesState

    main

    The InitialTypesState type allows you to customize how different JSON data types (like strings, numbers, booleans, etc.) are rendered within the view. You can specify the HTML element to use (as), custom styles, CSS classes, and a custom render function for each type.

    Supported type keys in InitialTypesState include:

    • Url (for URL strings)
    • Str (for general strings)
    • Undefined (for undefined)
    • Null (for null)
    • True / False (for booleans)
    • Date (for Date objects)
    • Float / Int / Bigint / Nan (for various number types)
    • Set / Map (for collection types)

    Each type configuration can use the render prop to access the specific value and key name being processed.

    import { InitialTypesState } from '@uiw/react-json-view'; // Assuming export path
    
    const customTypes: InitialTypesState<'span'> = {
      Str: {
        as: 'span',
        style: { color: 'orange' },
        children: 'string',
        render: (props, result) => (
          <span style={{ fontWeight: 'bold' }}>
            {result.value}
          </span>
        ),
      },
      // ... other types
    };
  5. Configure string shortening for TypeString

    main

    The TypeString component can automatically shorten long strings. This behavior is controlled by two settings in the global store:

    • shortenTextAfterLength: The maximum length before truncation (defaults to 30).
    • stringEllipsis: The string used to indicate truncation (defaults to '...').

    When a string is shortened, it becomes interactive: clicking the truncated text will toggle between the shortened and full version.

  6. Customize type rendering using the Types component

    main

    The Types component acts as a provider to inject custom type rendering configurations into the component tree. It requires an initial state object (of type InitialTypesState) and a dispatch function to manage state updates.

    Use this component to wrap parts of your application where you want to override the default visual representation of JSON data types.

    import { Types } from '@uiw/react-json-view';
    
    function MyCustomView({ customTypes, dispatch }) {
      return (
        <Types initial={customTypes} dispatch={dispatch}>
          {/* Your JSON view components here */}
        </Types>
      );
    }
  7. Access JsonView sub-components

    main

    The JsonView component acts as a namespace for several specialized sub-components. These can be used directly or accessed via the JsonView object.

    Type Components:

    • Bigint, Date (as JsonDate), False, Float, Int, Map (as JsonMap), Nan, Null, Set (as JsonSet), String (as JsonString), True, Undefined, Url.

    Symbol Components:

    • BraceLeft, BraceRight, BracketsLeft, BracketsRight, Arrow, Colon, Quote, ValueQuote.

    Section Components:

    • Copied, CountInfo, CountInfoExtra, Ellipsis, KeyName, Row.
  8. Customize JSON symbols with Quote, Colon, Arrow, and Brackets

    main
    The react-json-view library provides several specialized components to render JSON structural symbols (quotes, colons, arrows, and brackets). These components can be used to build custom UI for JSON trees. They are designed to work with the internal useSymbolsStore, allowing you to override their default behavior (the as property for changing the HTML element or the render function for custom rendering logic).
  9. Use useTypes and useTypesDispatch hooks

    main

    To interact with the type rendering state within your own custom components, use the following hooks:

    • useTypes(): Returns the current [state, dispatch] pair from useReducer, allowing you to read and update the InitialTypesState.
    • useTypesDispatch(): Returns only the dispatch function from the DispatchTypes context, useful for components that only need to trigger updates to the type configurations.
    import { useTypes, useTypesDispatch } from '@uiw/react-json-view';
    
    const MyComponent = () => {
      const [types, dispatch] = useTypes();
      const dispatchOnly = useTypesDispatch();
    
      // Access current type styles
      console.log(types.Str?.style);
    
      return <div>...</div>;
    };
  10. Render primitive types with Type components

    main

    The library provides specialized components for rendering various primitive and built-in JavaScript types. Most of these components support a render function via the store to allow custom rendering of both the type label and the value itself.

    Available type components include:

    • TypeString: Renders strings. Supports shortening long text based on shortenTextAfterLength and stringEllipsis settings. Clicking a shortened string toggles its full view.
    • TypeInt: Renders integers.
    • TypeFloat: Renders floating-point numbers.
    • TypeBigint: Renders BigInt values, appending n to the string representation.
    • TypeTrue / TypeFalse: Renders boolean values.
    • TypeUrl: Renders URL objects as clickable <a> tags.
    • TypeDate: Renders Date objects using toLocaleString().
    • TypeNull / TypeUndefined: Renders null or undefined literals.
    • TypeNan: Renders NaN values.
  11. Configure the initial state of the JSON view using Provider

    main

    The Provider component allows you to initialize the state of the JSON view, including configuration for indentation, sorting, and display behavior. You can pass an initialState object to customize these settings globally for the children of the provider.

    Key configuration options available in initialState include:

    • indentWidth: Number defining the indentation width (defaults to 15).
    • objectSortKeys: Boolean to determine if object keys should be sorted (defaults to false).
    • collapsed: Boolean to control initial collapsed state.
    • enableClipboard: Boolean to enable/disable clipboard functionality.
    • displayObjectSize: Boolean to show the size of objects.
    • stringEllipsis: String used for text truncation.
    • shortenTextAfterLength: Number defining when to truncate text.
    import { Provider } from '@uiw/react-json-view';
    
    const initialState = {
      indentWidth: 20,
      objectSortKeys: true,
      enableClipboard: true,
    };
    
    function App() {
      return (
        <Provider initialState={initialState}>
          <JsonView object={{ a: 1 }} />
        </Provider>
      );
    }
  12. Use SectionElementResult to access data in custom renders

    main

    When using a custom render function in SectionElementProps, you receive a SectionElementResult object which provides context about the data being rendered.

    SectionElementResult<T, K> contains:

    • value: The current value being rendered.
    • parentValue: The value of the parent object.
    • keyName: The name of the current key.
    • keys: An array of keys belonging to the parent object.