### Install react-json-view-lite
Source: https://github.com/anyroad/react-json-view-lite/blob/release/README.md
Install the library using npm. This command adds the package to your project's dependencies.
```bash
npm install --save react-json-view-lite
```
--------------------------------
### Override CSS Classes for Theming
Source: https://context7.com/anyroad/react-json-view-lite/llms.txt
Completely control the visual appearance by overriding individual CSS classes. This example demonstrates how to apply a custom dark theme using CSS class names.
```css
/* custom-json-theme.css */
.my-container {
background: #1a1a2e;
padding: 16px;
border-radius: 8px;
}
.my-string { color: #e94560; }
.my-number { color: #0f3460; }
.my-boolean { color: #16c79a; }
.my-null { color: #888; font-style: italic; }
.my-label { color: #eee; font-weight: bold; }
.my-punctuation { color: #666; }
.my-expand-icon::after { content: '+'; cursor: pointer; }
.my-collapse-icon::after { content: '-'; cursor: pointer; }
.my-collapsed::after { content: '...'; }
.my-child-container {
margin: 0;
padding: 0;
padding-left: 20px;
}
```
```tsx
import { JsonView, defaultStyles, StyleProps } from 'react-json-view-lite';
import './custom-json-theme.css';
const myCustomStyles: StyleProps = {
container: 'my-container',
basicChildStyle: 'my-basic-child',
childFieldsContainer: 'my-child-container',
label: 'my-label',
clickableLabel: 'my-label my-clickable',
stringValue: 'my-string',
numberValue: 'my-number',
booleanValue: 'my-boolean',
nullValue: 'my-null',
undefinedValue: 'my-null',
otherValue: 'my-other',
punctuation: 'my-punctuation',
expandIcon: 'my-expand-icon',
collapseIcon: 'my-collapse-icon',
collapsedContent: 'my-collapsed',
noQuotesForStringValues: false,
quotesForFieldNames: false,
ariaLables: { collapseJson: 'collapse', expandJson: 'expand' },
stringifyStringValues: false
};
```
--------------------------------
### Control Node Expansion with shouldExpandNode
Source: https://context7.com/anyroad/react-json-view-lite/llms.txt
Customize initial node expansion using the `shouldExpandNode` callback. Helpers like `allExpanded` and `collapseAllNested` are provided, or you can define custom logic.
```tsx
import { JsonView, defaultStyles, allExpanded, collapseAllNested } from 'react-json-view-lite';
import 'react-json-view-lite/dist/index.css';
const data = {
level0: {
level1: {
level2: {
deepValue: 'nested content'
}
}
},
items: [1, 2, 3, { nested: true }]
};
// All nodes expanded (default)
// Only root level expanded, nested objects collapsed
// Custom: expand only first 2 levels
const expandTwoLevels = (level: number) => level < 2;
// Custom: expand arrays but collapse objects
const expandArraysOnly = (level: number, value: any) => Array.isArray(value);
// Custom: expand specific fields by name
const expandSpecificFields = (level: number, value: any, field?: string) => {
return field === 'items' || field === 'level0';
};
// All nodes collapsed
const collapseAll = () => false;
```
--------------------------------
### Basic JsonView Component Usage
Source: https://context7.com/anyroad/react-json-view-lite/llms.txt
Render JSON data with default styles and all nodes expanded. Ensure the CSS file is imported for proper styling.
```tsx
import * as React from 'react';
import { JsonView, allExpanded, darkStyles, defaultStyles } from 'react-json-view-lite';
import 'react-json-view-lite/dist/index.css';
const jsonData = {
name: 'John Doe',
age: 30,
email: 'john@example.com',
address: {
street: '123 Main St',
city: 'New York',
country: 'USA'
},
hobbies: ['reading', 'coding', 'gaming'],
isActive: true,
metadata: null
};
function App() {
return (
{/* Light theme with all nodes expanded */}
{/* Dark theme */}
);
}
export default App;
```
--------------------------------
### Basic JSON View Usage
Source: https://github.com/anyroad/react-json-view-lite/blob/release/README.md
Render JSON data using the JsonView component. Import necessary components and styles. Use `allExpanded` to expand all nodes by default and choose between `defaultStyles` or `darkStyles`.
```tsx
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 (
);
};
export default App;
```
--------------------------------
### StyleProps Interface
Source: https://github.com/anyroad/react-json-view-lite/blob/release/README.md
Defines CSS class names and styling options for customizing the JSON viewer's appearance.
```APIDOC
### StyleProps
| Name | Type | Description |
| ----------------------- | ---------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| container | string | CSS class name for rendering parent block |
| childFieldsContainer | string | CSS class name for rendering parent block of array or object |
| basicChildStyle | string | CSS class name for rendering property block containing property name and value |
| collapseIcon | string | CSS class name for rendering button collapsing Object and Array nodes. Default content is `▾`. |
| expandIcon | string | CSS class name for rendering button expanding Object and Array nodes. Default content is `▸`. |
| collapsedContent | string | CSS class name for rendering placeholder when Object and Array nodes are collapsed. Default contents is `...`. |
| label | string | CSS class name for rendering property names |
| clickableLabel | string | CSS class name for rendering clickable property names (requires the `clickToExpandNode` prop to be true) |
| nullValue | string | CSS class name for rendering null values |
| undefinedValue | string | CSS class name for rendering undefined values |
| numberValue | string | CSS class name for rendering numeric values |
| stringValue | string | CSS class name for rendering string values |
| booleanValue | string | CSS class name for rendering boolean values |
| otherValue | string | CSS class name for rendering all other values except Object, Arrray, null, undefined, numeric, boolean and string |
| punctuation | string | CSS class name for rendering `,`, `[`, `]`, `{`, `}` |
| noQuotesForStringValues | boolean | whether or not to add double quotes when rendering string values, default value is `false` |
| quotesForFieldNames | boolean | whether or not to add double quotes when rendering field names, default value is `false` |
| ariaLables | AriaLables | Text to use for the `aria-label` properties |
| stringifyStringValues | boolean | whether or not to call `JSON.stringify` for string values in order to preserve escaped string characters like new line, tab or quotes |
```
--------------------------------
### Extra Exported Utilities
Source: https://github.com/anyroad/react-json-view-lite/blob/release/README.md
Provides utility functions and constants for controlling the JSON viewer's state and behavior.
```APIDOC
### Extra exported
| Name | Type | Description |
| ----------------- | ---------------------------- | --------------------------------------------------- |
| defaultStyles | StyleProps | Default styles for light background |
| darkStyles | StyleProps | Default styles for dark background |
| allExpanded | `() => boolean` | Always returns `true` |
| collapseAllNested | `(level: number) => boolean` | Returns `true` only for the first level (`level=0`) |
```
--------------------------------
### Enable Click to Expand Node
Source: https://context7.com/anyroad/react-json-view-lite/llms.txt
Set `clickToExpandNode` to `true` to allow users to expand or collapse nodes by clicking on their field names, not just the expand/collapse icon.
```tsx
import { JsonView, defaultStyles, allExpanded } from 'react-json-view-lite';
import 'react-json-view-lite/dist/index.css';
const data = {
server: {
host: 'localhost',
port: 3000,
ssl: false
},
database: {
connection: 'mongodb://localhost:27017',
name: 'myapp'
}
};
// Click anywhere on field name to expand/collapse
```
--------------------------------
### Intercept Expand/Collapse Events with beforeExpandChange
Source: https://context7.com/anyroad/react-json-view-lite/llms.txt
Use the `beforeExpandChange` hook to intercept and control expand/collapse actions. Return `false` to prevent the action, useful for conditional logic or analytics.
```tsx
import { JsonView, defaultStyles, NodeExpandingEvent } from 'react-json-view-lite';
import 'react-json-view-lite/dist/index.css';
import { useCallback, useState } from 'react';
function ControlledJsonView() {
const [expandedNodes, setExpandedNodes] = useState>(new Set());
const handleBeforeExpandChange = useCallback((event: NodeExpandingEvent): boolean => {
const { level, value, field, newExpandValue } = event;
// Log expansion events
console.log(`Node "${field}" at level ${level} will ${newExpandValue ? 'expand' : 'collapse'}`);
// Prevent expanding nodes deeper than level 3
if (newExpandValue && level >= 3) {
console.log('Expansion blocked: max depth reached');
return false;
}
// Prevent expanding large arrays (performance protection)
if (newExpandValue && Array.isArray(value) && value.length > 100) {
console.log('Expansion blocked: array too large');
return false;
}
// Allow the change
return true;
}, []);
const data = {
users: [
{ name: 'Alice', roles: ['admin', 'user'] },
{ name: 'Bob', roles: ['user'] }
],
settings: {
theme: 'dark',
notifications: { email: true, push: false }
}
};
return (
);
}
```
--------------------------------
### Compact Top Level Rendering
Source: https://context7.com/anyroad/react-json-view-lite/llms.txt
Use the `compactTopLevel` property to render objects without the top-level collapse button and indentation. This is useful for cleaner display of root-level properties.
```tsx
import { JsonView, defaultStyles, allExpanded } from 'react-json-view-lite';
import 'react-json-view-lite/dist/index.css';
const config = {
apiKey: 'abc123',
endpoint: 'https://api.example.com',
options: {
timeout: 5000,
retries: 3
}
};
// Standard rendering (with top-level collapse button)
// Compact top level (no collapse button for root object)
```
--------------------------------
### React JSON View Lite Component Props
Source: https://github.com/anyroad/react-json-view-lite/blob/release/README.md
This section outlines the available props for the React JSON View Lite component, including their types, default values, and descriptions.
```APIDOC
## React JSON View Lite Component Props
### Description
This section outlines the available props for the React JSON View Lite component, including their types, default values, and descriptions.
### Props
#### `data`
- **Type**: `Object` | `Array`
- **Default Value**: N/A
- **Description**: Data which should be rendered.
#### `style`
- **Type**: `StyleProps`
- **Default Value**: `defaultStyles`
- **Description**: Optional. CSS classes for rendering. Library provides two build-in implementations: `darkStyles`, `defaultStyles`.
#### `shouldExpandNode`
- **Type**: `(level: number, value: any, field?: string) => boolean`
- **Default Value**: `allExpanded`
- **Description**: Optional. Function which will be called during initial rendering for each Object and Array of the data in order to calculate should if this node be expanded. Note that this function will be called again to update the each node state once the property value changed. `level` startes from `0`, `field` does not have a value for the array element. Library provides two build-in implementations: `allExpanded` and `collapseAllNested`.
#### `clickToExpandNode`
- **Type**: `boolean`
- **Default Value**: `false`
- **Description**: Optional. Set to true if you want to expand/collapse nodes by clicking on the node itself.
#### `beforeExpandChange`
- **Type**: `(event: NodeExpandingEvent) => boolean`
- **Default Value**: `undefined`
- **Description**: Optional. Function which will be called before node expanded or collapsed. If the function returns `true` then expand/collapse process goes as usual, if it returns `false` then node state stay the same. For example, you can return `false` to change `shouldExpandNode` property in order to open only desired children nodes.
#### `compactTopLevel`
- **Type**: `boolean`
- **Default Value**: `false`
- **Description**: Optional. Set to true if you do not want to render top level collapse/expand button and indentation. Has no effect if the `data` parameter is not an Object.
### Interface: `NodeExpandingEvent`
#### Fields
- **`level`** (number) - level of expanded/collapsed node
- **`value`** (any) - Field value (object or array) to be expaneded/collapsed
- **`field`** (string?) - Field name
- **`newExpandValue`** (boolean) - if node is about to be expanded (`true`) or collapsed (`false`)
```
--------------------------------
### Memoize Callbacks with useCallback
Source: https://context7.com/anyroad/react-json-view-lite/llms.txt
Memoize callback functions using `useCallback` to prevent them from being recreated on every render. This is crucial for performance when passing callbacks as props to child components or when they are dependencies of other hooks.
```tsx
import { useCallback, useState } from 'react';
import { JsonView, defaultStyles } from 'react-json-view-lite';
import 'react-json-view-lite/dist/index.css';
function OptimizedJsonViewer({ initialData }: { initialData: object }) {
const [data, setData] = useState(initialData);
const [maxExpandLevel, setMaxExpandLevel] = useState(2);
// Memoize to prevent re-creation on every render
const shouldExpandNode = useCallback(
(level: number, value: any, field?: string) => {
return level < maxExpandLevel;
},
[maxExpandLevel] // Only recreate when maxExpandLevel changes
);
const handleBeforeExpandChange = useCallback(
(event: { level: number; newExpandValue: boolean }) => {
console.log(`Level ${event.level}: ${event.newExpandValue ? 'expanding' : 'collapsing'}`);
return true;
},
[] // Never recreates
);
return (
);
}
```
--------------------------------
### Render All Supported Data Types
Source: https://context7.com/anyroad/react-json-view-lite/llms.txt
The component automatically handles and renders various JavaScript data types, including primitives, special types like BigInt and Date, functions, and nested structures.
```tsx
import { JsonView, defaultStyles, allExpanded } from 'react-json-view-lite';
import 'react-json-view-lite/dist/index.css';
const allTypesDemo = {
// Primitive types
stringValue: 'Hello World',
emptyString: '',
numberValue: 42.5,
negativeNumber: -100,
booleanTrue: true,
booleanFalse: false,
nullValue: null,
undefinedValue: undefined,
// Special types
bigIntValue: BigInt('9007199254740991'), // Renders as "9007199254740991n"
dateValue: new Date('2024-01-15T10:30:00Z'), // Renders as ISO string
functionValue: () => console.log('hello'), // Renders as "function() { }"
// Collections
emptyArray: [],
emptyObject: {},
arrayOfMixed: [1, 'two', true, null, { nested: 'object' }],
// Nested structures
deepNesting: {
level1: {
level2: {
level3: {
value: 'deeply nested'
}
}
}
}
};
```
--------------------------------
### Custom Styles with StyleProps
Source: https://context7.com/anyroad/react-json-view-lite/llms.txt
Customize the JSON viewer's appearance by providing a `StyleProps` object. This allows for modifications like removing quotes from string values, adding quotes to field names, and preserving escaped characters.
```tsx
import { JsonView, defaultStyles, StyleProps } from 'react-json-view-lite';
import 'react-json-view-lite/dist/index.css';
// Custom style with modifications
const customStyles: StyleProps = {
...defaultStyles,
// Remove quotes from string values
noQuotesForStringValues: true,
// Add quotes to field names (JSON standard)
quotesForFieldNames: true,
// Preserve escaped characters in strings (newlines, tabs, etc.)
stringifyStringValues: true,
// Custom aria labels for accessibility
ariaLables: {
collapseJson: 'Collapse this section',
expandJson: 'Expand this section'
}
};
const data = {
message: 'Hello\nWorld\twith "quotes"',
count: 42,
active: true
};
// Output with stringifyStringValues: true shows escaped characters:
// "message": "Hello\nWorld\twith \"quotes\""
```
--------------------------------
### AriaLabels Interface
Source: https://github.com/anyroad/react-json-view-lite/blob/release/README.md
Defines ARIA labels for interactive elements within the JSON viewer.
```APIDOC
## Interface AriaLabels
| Field Name | Type | Description |
| ------------ | ------ | --------------------------------------------------------------------------------------- |
| collapseJson | string | `aria-label` property for the "collapse" node button. Default value is "collapse JSON". |
| expandJson | string | `aria-label` property for the "expand" node button. Default value is "expand JSON". |
```
--------------------------------
### Add Custom CSS for Child Fields Container
Source: https://github.com/anyroad/react-json-view-lite/blob/release/README.md
If using custom styles, ensure you include CSS for `.child-fields-container` to maintain proper layout for nested elements, as the component uses `ul` for its structure.
```css
.child-fields-container {
margin: 0;
padding: 0;
}
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.