### Install Material-UI Peer Dependencies
Source: https://github.com/texteainc/json-viewer/blob/main/docs/pages/migration/migration-v3.mdx
Installs the required Material-UI core dependencies. These are now necessary as peer dependencies starting from v3 and are no longer included directly in the package.
```bash
npm install @mui/material @emotion/react @emotion/styled
```
--------------------------------
### Nextra Theme Setup for Next.js Application
Source: https://github.com/texteainc/json-viewer/blob/main/docs/pages/_app.mdx
This snippet demonstrates the basic setup for integrating the Nextra theme into a Next.js application. It ensures that the theme's styles are applied and the main component renders correctly.
```javascript
import 'nextra-theme-docs/style.css'
export default function Nextra({ Component, pageProps }) {
return
}
```
--------------------------------
### Install @textea/json-viewer with npm, yarn, or pnpm
Source: https://github.com/texteainc/json-viewer/blob/main/docs/pages/index.mdx
Installs the @textea/json-viewer package along with its peer dependencies from Material-UI. Ensure Material-UI and its dependencies are installed before proceeding.
```bash
npm install @textea/json-viewer @mui/material @emotion/react @emotion/styled
```
```bash
yarn add @textea/json-viewer @mui/material @emotion/react @emotion/styled
```
```bash
pnpm add @textea/json-viewer @mui/material @emotion/react @emotion/styled
```
--------------------------------
### Update Dependencies
Source: https://github.com/texteainc/json-viewer/blob/main/docs/pages/migration/migration-v4.mdx
Installs the latest version of @textea/json-viewer (v4) and @mui/material (v6). Users of Material-UI should also consult the MUI v6 migration guide for related changes.
```bash
npm install @textea/json-viewer@^4.0.0
npm install @mui/material@^6.0.0
```
--------------------------------
### Install/Update @textea/json-viewer Package
Source: https://github.com/texteainc/json-viewer/blob/main/docs/pages/migration/migration-v3.mdx
Installs or updates the @textea/json-viewer package to version 3.0.0 or higher. This is the first step in migrating to the latest version.
```bash
npm install @textea/json-viewer@^3.0.0
```
--------------------------------
### Optimize Large Datasets with JsonViewer
Source: https://context7.com/texteainc/json-viewer/llms.txt
This example shows how to configure JsonViewer for large datasets using options like `maxDisplayLength`, `groupArraysAfterLength`, `collapseStringsAfterLength`, and `defaultInspectDepth`. It also includes key sorting and display size configurations. Depends on '@textea/json-viewer'.
```jsx
import { JsonViewer } from '@textea/json-viewer'
function LargeDataViewer() {
// Generate large dataset
const largeArray = Array.from({ length: 1000 }, (_, i) => ({
id: i,
name: `Item ${i}`,
data: Array.from({ length: 50 }, (_, j) => `value_${j}`)
}))
const largeObject = Object.fromEntries(
Array.from({ length: 500 }, (_, i) => [`key_${i}`, `value_${i}`])
)
const data = {
largeArray,
largeObject,
metadata: {
arrayLength: largeArray.length,
objectKeys: Object.keys(largeObject).length
}
}
return (
)
}
```
--------------------------------
### Advanced Configuration for JSON Viewer with Path-Based Control
Source: https://context7.com/texteainc/json-viewer/llms.txt
This example showcases advanced configuration options for the JsonViewer component, allowing path-based control over editing, deletion, size display, and expansion behavior. It utilizes callback functions like `isEditable`, `isDeletable`, `shouldDisplaySize`, and `defaultInspectControl` to customize the viewer's interactivity and presentation. The `JsonViewer` component from '@textea/json-viewer' is the primary dependency.
```jsx
import { JsonViewer } from '@textea/json-viewer'
function AdvancedViewer() {
const sensitiveData = {
public: {
name: "John Doe",
email: "john@example.com"
},
private: {
ssn: "123-45-6789",
apiKey: "sk_live_abcdef123456",
password: "hashed_value"
},
stats: {
logins: 42,
lastActive: new Date("2024-01-15")
}
}
// Only allow editing public fields
const isEditable = (path, value) => {
return path[0] === 'public' && path.length > 1
}
// Only allow deleting from stats
const isDeletable = (path, value) => {
return path[0] === 'stats'
}
// Show size only for objects and arrays with more than 3 items
const shouldDisplaySize = (path, value) => {
if (typeof value !== 'object' || value === null) return false
const size = Array.isArray(value) ? value.length : Object.keys(value).length
return size > 3
}
// Auto-expand only the public section
const shouldExpand = (path, value) => {
return path.length === 0 || path[0] === 'public'
}
return (
{
console.log('Change:', path, oldVal, '→', newVal)
}}
/>
)
}
```
--------------------------------
### Custom Data Types with defineDataType in React
Source: https://context7.com/texteainc/json-viewer/llms.txt
Illustrates how to extend the JsonViewer with custom data type renderers using the `defineDataType` function. This example defines two custom types: one for displaying image URLs and another for visually representing color hex codes. It shows how to create a `valueTypes` array containing these custom definitions and pass it to the `JsonViewer` component for specialized rendering.
```jsx
import { JsonViewer, defineDataType } from '@textea/json-viewer'
// Custom data type for displaying images from URLs
const imageDataType = defineDataType({
is: (value) => typeof value === 'string' && /\.(jpg|jpeg|png|gif|webp)$/i.test(value),
Component: (props) => (
)
})
// Custom data type for color hex codes
const colorDataType = defineDataType({
is: (value) => typeof value === 'string' && /^#[0-9A-F]{6}$/i.test(value),
Component: (props) => (
"{props.value}"
)
})
const productData = {
name: "Premium T-Shirt",
thumbnail: "https://example.com/tshirt.jpg",
colors: ["#FF5733", "#33FF57", "#3357FF"],
price: 29.99
}
function ProductViewer() {
return (
)
}
```
--------------------------------
### Extend stringType to create a Link Data Type (JS)
Source: https://github.com/texteainc/json-viewer/blob/main/docs/pages/how-to/data-types.mdx
Extends the built-in `stringType` to create a `linkType` in JavaScript. This type identifies strings starting with 'http' and adds an 'Open' button to display them in a new tab.
```jsx
import { defineDataType, stringType } from '@textea/json-viewer'
import { Button } from '@mui/material'
const linkType = defineDataType({
...stringType,
is (value) {
return typeof value === 'string' && value.startsWith('http')
},
PostComponent: (props) => (
)
})
```
--------------------------------
### Using Custom Image Data Type in JsonViewer Component
Source: https://github.com/texteainc/json-viewer/blob/main/docs/pages/how-to/data-types.mdx
This snippet shows how to apply a custom data type, like the `imageType` defined previously, to the `JsonViewer` component. By passing the custom type in the `valueTypes` prop, the JSON viewer will use the defined rendering logic for matching values. This example assumes the `imageType` has already been defined.
```jsx
```
--------------------------------
### Extend stringType to create a Link Data Type (TS)
Source: https://github.com/texteainc/json-viewer/blob/main/docs/pages/how-to/data-types.mdx
Extends the built-in `stringType` to create a `linkType` in TypeScript. It checks for strings starting with 'http' and appends a button to open the link in a new tab, using generic type `string`.
```tsx
import { defineDataType, stringType } from '@textea/json-viewer'
import { Button } from '@mui/material'
const linkType = defineDataType({
...stringType,
is (value) {
return typeof value === 'string' && value.startsWith('http')
},
PostComponent: (props) => (
)
})
```
--------------------------------
### CDN Integration for JsonViewer
Source: https://github.com/texteainc/json-viewer/blob/main/README.md
Provides an HTML snippet demonstrating how to include the JsonViewer library via a CDN and initialize it with a data object. This method is suitable for projects not using a module bundler.
```html
```
--------------------------------
### Basic JsonViewer Component Usage in React
Source: https://context7.com/texteainc/json-viewer/llms.txt
Demonstrates the basic implementation of the JsonViewer component in a React application. It shows how to import the component, define a sample data object (including nested objects, arrays, Maps, and Dates), and render it with various props like `rootName`, `defaultInspectDepth`, `theme`, `enableClipboard`, `displayDataTypes`, and `displaySize` for customization.
```jsx
import { JsonViewer } from '@textea/json-viewer'
// Basic usage with an object
const data = {
name: "John Doe",
age: 30,
email: "john@example.com",
address: {
street: "123 Main St",
city: "Springfield",
coordinates: { lat: 42.1234, lng: -71.5678 }
},
hobbies: ["reading", "gaming", "cooking"],
isActive: true,
metadata: new Map([
["created", new Date("2024-01-15")],
["views", 1523]
])
}
function App() {
return (
)
}
```
--------------------------------
### JSON Viewer Configuration Props
Source: https://github.com/texteainc/json-viewer/blob/main/docs/pages/apis.mdx
This section details the available properties for configuring the JSON Viewer component, including display options and update highlighting.
```APIDOC
## JSON Viewer Component Props
### Description
Configuration options for the JSON Viewer component.
### Parameters
#### Request Body (Props)
- **displaySize** (boolean | (path, currentValue) => boolean) - Required/Optional - Whether to display the size of `Object`, `Array`, `Map`, and `Set`. Provide a function to customize this behavior by returning a boolean based on the value and path. Defaults to `true`.
- **displayComma** (boolean) - Required/Optional - Whether to display commas at the end of the line. Defaults to `true`.
- **highlightUpdates** (boolean) - Required/Optional - Whether to highlight updates. Defaults to `true`.
### Request Example
```json
{
"displaySize": true,
"displayComma": false,
"highlightUpdates": true
}
```
### Response
#### Success Response (200)
This component does not have a direct API endpoint for responses. Configuration is passed as props.
#### Response Example
N/A
```
--------------------------------
### Use @textea/json-viewer from CDN in HTML
Source: https://github.com/texteainc/json-viewer/blob/main/docs/pages/index.mdx
Includes the @textea/json-viewer library from a CDN and renders JSON data to a specified HTML element. This method is suitable for quick integration without a build process.
```html
```
--------------------------------
### Mapping from react-json-view
Source: https://github.com/texteainc/json-viewer/blob/main/docs/pages/apis.mdx
This section outlines the mapping of properties from the react-json-view library to this JSON Viewer component.
```APIDOC
## Mapping from react-json-view
### Description
This section details the direct mappings of properties from the `mac-s-g/react-json-view` library to this JSON Viewer component.
### Parameters
#### Request Body (Props Mapping)
- **name** (string) - See `rootName`.
- **src** (any) - See `value`.
- **collapsed** (boolean) - Set `defaultInspectDepth` to `0` to collapse all.
```
--------------------------------
### Rename displayObjectSize to displaySize Prop
Source: https://github.com/texteainc/json-viewer/blob/main/docs/pages/migration/migration-v3.mdx
Illustrates the renaming of the `displayObjectSize` prop to `displaySize` for improved clarity. The `displaySize` prop now accepts a function that returns a boolean, allowing for customized behavior based on the value and its path within the JSON structure.
```jsx
{
if (Array.isArray(value)) return false
if (value instanceof Map) return true
return true
}}
value={value}
/>
```
--------------------------------
### Basic JSON Viewer Component in React
Source: https://github.com/texteainc/json-viewer/blob/main/docs/pages/index.mdx
Renders a JSON object using the JsonViewer component from @textea/json-viewer. This is the most straightforward way to display JSON data within a React application.
```tsx
import { JsonViewer } from '@textea/json-viewer'
const object = {
/* my json object */
}
const Component = () =>
```
--------------------------------
### Editable Data with onChange Callback in React
Source: https://context7.com/texteainc/json-viewer/llms.txt
Demonstrates how to enable inline editing for data within the JsonViewer component by setting the `editable` prop to `true` and providing an `onChange` callback function. The `handleChange` function logs changes, uses `applyValue` to create an updated state object, and then updates the component's state using `useState`. This allows for interactive modification of data structures.
```jsx
import { JsonViewer, applyValue } from '@textea/json-viewer'
import { useState } from 'react'
function EditableConfig() {
const [config, setConfig] = useState({
apiUrl: "https://api.example.com",
timeout: 5000,
retries: 3,
features: {
darkMode: true,
notifications: false,
analytics: true
}
})
const handleChange = (path, oldValue, newValue) => {
console.log(`Changed ${path.join('.')} from ${oldValue} to ${newValue}`)
// Apply the change to create a new state object
const updatedConfig = applyValue(config, path, newValue)
setConfig(updatedConfig)
// Optionally persist to backend
// await saveConfig(updatedConfig)
}
return (
)
}
```
--------------------------------
### Define Custom Base 16 Theme for JsonViewer
Source: https://github.com/texteainc/json-viewer/blob/main/docs/pages/how-to/styling.mdx
Integrate custom color palettes using the Base 16 theme format by importing a theme object and passing it to the `theme` prop of the JsonViewer component for fine-grained visual control.
```typescript
import type { NamedColorspace } from '@textea/json-viewer'
export const ocean: NamedColorspace = {
scheme: 'Ocean',
author: 'Chris Kempson (http://chriskempson.com)',
base00: '#2b303b',
base01: '#343d46',
base02: '#4f5b66',
base03: '#65737e',
base04: '#a7adba',
base05: '#c0c5ce',
base06: '#dfe1e8',
base07: '#eff1f5',
base08: '#bf616a',
base09: '#d08770',
base0A: '#ebcb8b',
base0B: '#a3be8c',
base0C: '#96b5b4',
base0D: '#8fa1b3',
base0E: '#b48ead',
base0F: '#ab7967'
}
```
--------------------------------
### Custom Clipboard Copy Handler for JSON Viewer
Source: https://context7.com/texteainc/json-viewer/llms.txt
Allows customization of the clipboard copy functionality. Developers can define a custom handler to format the data before copying, providing more control over what is stored in the clipboard. Requires importing 'safeStringify' from '@textea/json-viewer'.
```jsx
import { JsonViewer, safeStringify } from '@textea/json-viewer'
function App() {
const logData = {
timestamp: Date.now(),
level: "error",
message: "Database connection failed",
stack: new Error("Connection timeout").stack,
context: {
userId: 12345,
action: "fetchUserData"
}
}
const handleCopy = async (path, value, copy) => {
// Custom copy logic
const pathString = path.join('.')
// Format the copied content
const formattedValue = typeof value === 'object'
? safeStringify(value, 2)
: String(value)
const copyText = `// Path: ${pathString}\n${formattedValue}`
// Use the provided copy function
await copy(copyText)
// Show notification
console.log(`Copied ${pathString} to clipboard`)
// Track analytics
// analytics.track('json_viewer_copy', { path: pathString })
}
return (
)
}
```
--------------------------------
### Select Callback for Interactive JSON Viewer Selection
Source: https://context7.com/texteainc/json-viewer/llms.txt
This snippet demonstrates how to use the `onSelect` callback with the JsonViewer component to track user clicks on values. It updates the state with the selected path and value, allowing integration with other UI components for displaying selection details. This requires the `JsonViewer` and `useState` hook from React.
```jsx
import { JsonViewer, getPathValue } from '@textea/json-viewer'
import { useState } from 'react'
function InteractiveViewer() {
const [selectedPath, setSelectedPath] = useState(null)
const [selectedValue, setSelectedValue] = useState(null)
const documentData = {
title: "Annual Report 2024",
sections: [
{
heading: "Executive Summary",
content: "Lorem ipsum...",
wordCount: 450
},
{
heading: "Financial Overview",
content: "Detailed analysis...",
wordCount: 1200
}
],
metadata: {
author: "Jane Smith",
created: "2024-01-15",
version: "1.2.3"
}
}
const handleSelect = (path, value) => {
setSelectedPath(path)
setSelectedValue(value)
}
return (
{selectedPath && (
Selection Details
Path: {selectedPath.join(' → ')}
Type: {typeof selectedValue}
Value:
{JSON.stringify(selectedValue, null, 2)}
)}
)
}
```
--------------------------------
### Handle Circular References with JsonViewer
Source: https://context7.com/texteainc/json-viewer/llms.txt
Demonstrates how to use JsonViewer to automatically detect and safely handle circular references within data structures. The `isCycleReference` utility function can be used for programmatic checks. This requires '@textea/json-viewer'.
```jsx
import { JsonViewer, isCycleReference } from '@textea/json-viewer'
function CircularDataViewer() {
// Create circular reference
const parent = { name: "Parent", children: [] }
const child1 = { name: "Child 1", parent: parent }
const child2 = { name: "Child 2", parent: parent }
parent.children = [child1, child2]
// Create self-reference
const node = { id: 1, value: "Root" }
node.self = node
const data = {
circularFamily: parent,
selfReference: node,
normalData: { a: 1, b: 2 }
}
// Check for circular reference programmatically
const checkCircular = () => {
const path = ['circularFamily', 'children', 0, 'parent']
const result = isCycleReference(data, path, parent)
console.log('Is circular?', result) // Returns the path string if circular
}
return (
)
}
```
--------------------------------
### Custom Theme with Base16 Colors
Source: https://context7.com/texteainc/json-viewer/llms.txt
Applies a custom color scheme to the JSON Viewer using Base16 color definitions. This allows for full control over the visual appearance of the JSON data. Ensure the 'Colorspace' type is imported from '@textea/json-viewer'.
```jsx
import { JsonViewer } from '@textea/json-viewer'
import type { Colorspace } from '@textea/json-viewer'
// Custom ocean theme
const oceanTheme: Colorspace = {
base00: '#2b303b', // background
base01: '#343d46', // lighter background
base02: '#4f5b66', // selection background
base03: '#65737e', // comments, invisibles
base04: '#a7adba', // dark foreground
base05: '#c0c5ce', // default foreground
base06: '#dfe1e8', // light foreground
base07: '#eff1f5', // light background
base08: '#bf616a', // red
base09: '#d08770', // orange
base0A: '#ebcb8b', // yellow
base0B: '#a3be8c', // green
base0C: '#96b5b4', // cyan
base0D: '#8fa1b3', // blue
base0E: '#b48ead', // purple
base0F: '#ab7967' // brown
}
const apiResponse = {
status: 200,
message: "Request successful",
data: {
users: [
{ id: 1, name: "Alice", role: "admin" },
{ id: 2, name: "Bob", role: "user" }
],
timestamp: new Date().toISOString()
}
}
function ThemedViewer() {
return (
)
}
```
--------------------------------
### Custom Data Type for Image Display (React)
Source: https://github.com/texteainc/json-viewer/blob/main/README.md
Shows how to define and use a custom data type to render specific values, like images, within the JsonViewer. This involves using defineDataType to specify the condition for the type and the component to render.
```jsx
import { JsonViewer, defineDataType } from '@textea/json-viewer'
const object = {
image: 'https://i.imgur.com/1bX5QH6.jpg'
// ... other values
}
// Let's define a data type for image
const imageDataType = defineDataType({
is: (value) => typeof value === 'string' && value.startsWith('https://i.imgur.com'),
Component: (props) =>
})
const Component = () =>
```
--------------------------------
### Add and Delete Operations for JSON Viewer
Source: https://context7.com/texteainc/json-viewer/llms.txt
Enables users to add new entries and delete existing ones within the JSON Viewer. Custom callback functions handle the logic for these operations, allowing for dynamic data manipulation. Requires importing 'applyValue' and 'deleteValue' from '@textea/json-viewer'.
```jsx
import { JsonViewer, applyValue, deleteValue } from '@textea/json-viewer'
import { useState } from 'react'
function DynamicListEditor() {
const [data, setData] = useState({
users: [
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" }
],
settings: {
theme: "dark",
language: "en"
}
})
const handleAdd = (path) => {
console.log('Add requested at path:', path)
// Determine what to add based on path
const parentValue = path.reduce((obj, key) => obj?.[key], data)
let newValue
if (Array.isArray(parentValue)) {
newValue = { id: Date.now(), name: "New Item" }
const newArray = [...parentValue, newValue]
setData(applyValue(data, path, newArray))
} else if (typeof parentValue === 'object') {
const newKey = `new_key_${Date.now()}`
const newObject = { ...parentValue, [newKey]: "new value" }
setData(applyValue(data, path, newObject))
}
}
const handleDelete = (path, value) => {
console.log('Delete requested:', path, value)
if (window.confirm(`Delete ${path.join('.')}?`)) {
const updated = deleteValue(data, path, value)
setData(updated)
}
}
return (
path.length > 1} // Don't allow deleting root
onAdd={handleAdd}
onDelete={handleDelete}
editable={true}
onChange={(path, oldVal, newVal) => {
setData(applyValue(data, path, newVal))
}}
/>
)
}
```
--------------------------------
### Replace createDataType with defineDataType
Source: https://github.com/texteainc/json-viewer/blob/main/docs/pages/migration/migration-v4.mdx
Demonstrates the API change from using `createDataType` (deprecated in v3, removed in v4) to the recommended `defineDataType` for defining data types within the JSON viewer. This is a breaking change for developers relying on the old method.
```javascript
// Before v4 (deprecated in v3, removed in v4):
// const myDataType = createDataType('myType', ...);
// In v4 and later:
const myDataType = defineDataType('myType', ...);
```
--------------------------------
### Set JsonViewer Theme
Source: https://github.com/texteainc/json-viewer/blob/main/docs/pages/how-to/styling.mdx
Control the color theme of the JsonViewer component by using the `theme` prop. Available options include 'light', 'dark', and 'auto', which dynamically adjusts to the system's theme settings. The component also applies specific classes for theme reflection.
```jsx
```
--------------------------------
### Apply Styles and Classes to JsonViewer
Source: https://github.com/texteainc/json-viewer/blob/main/docs/pages/how-to/styling.mdx
Customize the visual presentation of the JsonViewer component by passing inline styles via the `style` prop, applying custom CSS classes with the `className` prop, or using the `sx` prop for Material UI-based styling.
```jsx
```
--------------------------------
### Define Custom Data Types with JsonViewer
Source: https://context7.com/texteainc/json-viewer/llms.txt
This snippet shows how to use `defineEasyType` to create custom data types like email and URL. It includes validation, custom rendering, and serialization/deserialization logic. Dependencies include '@textea/json-viewer'.
```jsx
import { JsonViewer, defineEasyType } from '@textea/json-viewer'
// Create a custom type for email addresses
const emailType = defineEasyType({
is: (value) => {
if (typeof value !== 'string') return false
return /^[^s@]+@[^s@]+.[^s@]+$/.test(value)
},
type: 'email',
colorKey: 'base0C',
displayTypeLabel: true,
serialize: (value) => value,
deserialize: (value) => {
if (!/^[^s@]+@[^s@]+.[^s@]+$/.test(value)) {
throw new Error('Invalid email format')
}
return value
},
Renderer: ({ value }) => (
e.stopPropagation()}
>
{value}
)
})
// Create a custom type for URLs
const urlType = defineEasyType({
is: (value) => {
if (typeof value !== 'string') return false
try {
new URL(value)
return value.startsWith('http')
} catch {
return false
}
},
type: 'url',
colorKey: 'base0D',
serialize: (value) => value,
deserialize: (value) => {
try {
new URL(value)
return value
} catch {
throw new Error('Invalid URL')
}
},
Renderer: ({ value }) => (
e.stopPropagation()}
>
{value}
)
})
const contactData = {
name: "Jane Smith",
email: "jane@company.com",
website: "https://company.com",
github: "https://github.com/janesmith",
linkedin: "https://linkedin.com/in/janesmith"
}
function ContactViewer() {
return (
)
}
```
--------------------------------
### Define new boolean type with defineEasyType for Icon Display
Source: https://github.com/texteainc/json-viewer/blob/main/docs/pages/how-to/built-in-types.mdx
This snippet shows an alternative method to display boolean values as icons using `defineEasyType`. This helper function simplifies data type creation by automatically handling type labels and colors. It requires importing `defineEasyType` and `booleanType`. The `Renderer` property is used to specify how the boolean value should be displayed as an icon.
```tsx
import { defineEasyType, booleanType } from '@textea/json-viewer'
const toggleBoolType = defineEasyType({
...booleanType,
type: 'bool',
colorKey: 'base0E',
Renderer: ({ value }) => (
{value ? '✔️' : '❌'}
)
})
```
--------------------------------
### Customize JsonViewer Appearance with CSS
Source: https://github.com/texteainc/json-viewer/blob/main/docs/pages/how-to/styling.mdx
Target specific elements within the JsonViewer's DOM structure using predefined class names like `data-object-start` or `json-type-label` to apply custom CSS rules and modify the component's detailed appearance.
```css
.json-viewer .data-object-start {
color: red;
}
```
--------------------------------
### Update createDataType to defineDataType
Source: https://github.com/texteainc/json-viewer/blob/main/docs/pages/migration/migration-v3.mdx
Demonstrates the refactoring of a custom data type definition. The `createDataType` function has been renamed to `defineDataType` and now accepts an object with `is` and `Component` properties for defining custom data types, including support for serialization and deserialization.
```diff
- createDataType(
- (value) => typeof value === 'string' && value.startsWith('https://i.imgur.com'),
- (props) =>
- )
+ defineDataType({
+ is: (value) => typeof value === 'string' && value.startsWith('https://i.imgur.com'),
+ Component: (props) =>
+ })
```
--------------------------------
### Customize Date Format using defineEasyType (JS)
Source: https://github.com/texteainc/json-viewer/blob/main/docs/pages/how-to/data-types.mdx
Customizes the display format for Date objects using `defineEasyType` in JavaScript. It sets a specific type, color key, and provides a renderer to show only the date part in ISO format.
```jsx
import { defineEasyType } from '@textea/json-viewer'
const myDateType = defineEasyType({
is: (value) => value instanceof Date,
type: 'date',
colorKey: 'base0D',
Renderer: ({ value }) => <>{value.toISOString().split('T')[0]}>
})
```
--------------------------------
### Define Image Data Type in JS/TS for JsonViewer
Source: https://github.com/texteainc/json-viewer/blob/main/docs/pages/how-to/data-types.mdx
This snippet demonstrates defining a custom data type for image URLs. The `is` function checks if a string is a valid URL ending with '.jpg'. The `Component` renders the URL as an `` element. This allows previewing images directly within the JSON viewer. It requires the '@textea/json-viewer' library.
```jsx
import { defineDataType } from '@textea/json-viewer'
const imageType = defineDataType({
is: (value) => {
if (typeof value !== 'string') return false
try {
const url = new URL(value)
return url.pathname.endsWith('.jpg')
} catch {
return false
}
},
Component: (props) => {
return (
)
}
})
```
```tsx
import { defineDataType } from '@textea/json-viewer'
const imageType = defineDataType({
is: (value) => {
if (typeof value !== 'string') return false
try {
const url = new URL(value)
return url.pathname.endsWith('.jpg')
} catch {
return false
}
},
Component: (props) => {
return (
)
}
})
```
--------------------------------
### Customize Date Format using defineEasyType (TS)
Source: https://github.com/texteainc/json-viewer/blob/main/docs/pages/how-to/data-types.mdx
Customizes the display format for Date objects using `defineEasyType` in TypeScript. It specifies the generic type as Date and configures rendering to show the date part of an ISO string.
```tsx
import { defineEasyType } from '@textea/json-viewer'
const myDateType = defineEasyType({
is: (value) => value instanceof Date,
type: 'date',
colorKey: 'base0D',
Renderer: ({ value }) => <>{value.toISOString().split('T')[0]}>
})
```
--------------------------------
### Override booleanType Component for Icon Display
Source: https://github.com/texteainc/json-viewer/blob/main/docs/pages/how-to/built-in-types.mdx
This snippet demonstrates how to override the default component for boolean types in JSON Viewer to display them as icons (✔️ for true, ❌ for false). It requires importing `JsonViewer`, `defineDataType`, and `booleanType` from '@textea/json-viewer'. The `Component` property of the defined data type is updated to render the boolean value as an icon.
```tsx
import { JsonViewer, defineDataType, booleanType } from '@textea/json-viewer'
import { Button } from '@mui/material'
const toggleBoolType = defineDataType({
...booleanType,
Component: ({ value }) => (
{value ? '✔️' : '❌'}
)
})
```
--------------------------------
### Define URL Data Type for JsonViewer (JS)
Source: https://github.com/texteainc/json-viewer/blob/main/docs/pages/how-to/data-types.mdx
Defines a custom data type for URL objects using `defineDataType` in JavaScript. It checks if a value is an instance of URL and renders it as a clickable link.
```jsx
import { defineDataType } from '@textea/json-viewer'
const urlType = defineDataType({
is: (value) => value instanceof URL,
Component: (props) => {
const url = props.value.toString()
return (
{url}
)
}
})
```
--------------------------------
### Define URL Data Type for JsonViewer (TS)
Source: https://github.com/texteainc/json-viewer/blob/main/docs/pages/how-to/data-types.mdx
Defines a custom data type for URL objects using `defineDataType` in TypeScript. It specifies the generic type as URL and renders it as an interactive hyperlink.
```tsx
import { defineDataType } from '@textea/json-viewer'
const urlType = defineDataType({
is: (value) => value instanceof URL,
Component: (props) => {
const url = props.value.toString()
return (
{url}
)
}
})
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.