### Install json-edit-react
Source: https://github.com/carlosnz/json-edit-react/blob/main/README.md
Install the library using npm or yarn package managers.
```sh
# Depending on your package manager:
npm i json-edit-react
# OR
yarn add json-edit-react
```
--------------------------------
### Example NewKeyOptionsFunction for Settings Keys
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/types.md
Provides an example of NewKeyOptionsFunction to offer a dropdown of specific keys for a 'settings' node.
```typescript
const newKeyOptions: NewKeyOptionsFunction = ({ key }) => {
if (key === 'settings') {
return ['theme', 'language', 'timezone', 'notifications']
}
return null // No restriction
}
```
--------------------------------
### Install Dependencies with Yarn
Source: https://github.com/carlosnz/json-edit-react/blob/main/custom-component-library/README.md
Use this command to install project dependencies within the custom-component-library folder.
```bash
yarn install
```
--------------------------------
### Complete Custom Theme Example
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/api-reference/themes.md
An example of a comprehensive custom theme, including fragments and detailed styles for various JSON elements and icons. This theme can be applied to the JsonEditor component.
```typescript
const customTheme = {
displayName: 'My Custom Theme',
fragments: {
iconBase: {
fontSize: '120%',
marginRight: '0.8em',
cursor: 'pointer',
},
readonlyStyle: {
color: '#999',
fontStyle: 'italic',
opacity: 0.7,
}
},
styles: {
container: {
backgroundColor: '#fafafa',
fontFamily: 'Menlo, monospace',
color: '#333',
},
property: {
color: '#333',
fontWeight: '500',
},
bracket: {
color: '#666',
fontWeight: 'bold',
},
string: 'rgb(200, 40, 41)',
number: 'rgb(38, 139, 210)',
boolean: 'rgb(42, 161, 152)',
null: {
color: 'rgb(220, 50, 47)',
fontVariant: 'small-caps',
fontWeight: 'bold'
},
input: {
backgroundColor: '#fff',
color: '#333',
border: '1px solid #ccc',
padding: '0.4em 0.6em',
fontFamily: 'inherit',
},
error: {
color: 'red',
fontWeight: 'bold',
fontSize: '0.85em',
},
iconEdit: 'iconBase',
iconDelete: ['iconBase', { color: 'red' }],
iconAdd: 'iconBase',
iconCopy: 'iconBase',
iconOk: ['iconBase', { color: 'green' }],
iconCancel: ['iconBase', { color: 'red' }],
}
}
```
--------------------------------
### CSS Example: Scale with CSS
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/api-reference/themes.md
Demonstrates scaling the JsonEditor component by applying a font-size to its container class using CSS.
```css
.jer-container {
font-size: 18px;
}
```
--------------------------------
### useKeyboardListener Usage Example
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/api-reference/icons-components.md
Example of using the useKeyboardListener hook to attach keyboard event handlers to an input element.
```typescript
import { useKeyboardListener } from 'json-edit-react'
const MyInput = () => {
const handleKeyboard = useKeyboardListener({
confirm: () => console.log('Confirmed'),
cancel: () => console.log('Cancelled')
})
return
}
```
--------------------------------
### Quick Start with JsonEditor
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/README.md
Integrate the JsonEditor component into your React application. This example shows how to manage JSON data state using useState.
```typescript
import React, { useState } from 'react'
import { JsonEditor } from 'json-edit-react'
export function App() {
const [data, setData] = useState({
name: 'John',
age: 30,
active: true
})
return (
)
}
```
--------------------------------
### KeyboardControls Usage Example
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/types.md
Shows how to customize keyboard shortcuts for the JsonEditor, such as changing the confirm key to Meta+Enter.
```typescript
```
--------------------------------
### TypeScript Example: Color Independence (Good Practice)
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/api-reference/themes.md
Illustrates a good practice for theme styling where color is not the sole indicator of meaning. This example uses color, font style, and text decoration to differentiate properties.
```typescript
// GOOD: Color + additional visual cues
const goodTheme = {
styles: {
property: ({ key }) => {
if (key.startsWith('_')) {
return {
color: '#999',
fontStyle: 'italic',
textDecoration: 'underline'
}
}
return null
}
}
}
```
--------------------------------
### OnChangeFunction Usage Example
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/types.md
Provides an example of implementing the `OnChangeFunction` callback to control input values, such as preventing negative numbers or forcing uppercase for specific fields.
```typescript
const handleChange: OnChangeFunction = ({ newValue, name, path }) => {
// Prevent negative numbers
if (typeof newValue === 'number' && newValue < 0) return 0
// Force uppercase for certain keys
if (name === 'code' && typeof newValue === 'string') {
return newValue.toUpperCase()
}
return newValue
}
```
--------------------------------
### StringDisplay Usage Example
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/api-reference/icons-components.md
Demonstrates how to use the StringDisplay component within a custom React component, applying custom styles.
```typescript
import { StringDisplay } from 'json-edit-react'
const MyCustomString = ({ nodeData, styles, ...props }) => (
Value:
)
```
--------------------------------
### Example CustomTextFunction for Item Count
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/types.md
Shows an example of CustomTextFunction to customize the display text for items, like showing the number of users.
```typescript
const customText: CustomTextDefinitions = {
ITEMS_MULTIPLE: ({ key, size }) => {
if (key === 'users') return `${size} users`
return null // Use default
}
}
```
--------------------------------
### Example DefaultValueFunction for New Properties
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/types.md
Demonstrates DefaultValueFunction to set initial values for new properties, such as a user object or a creation timestamp.
```typescript
const defaultValue: DefaultValueFunction = ({ key }, newKey) => {
if (key === 'users') return { name: '', email: '' }
if (newKey === 'createdAt') return new Date().toISOString()
return 'New value'
}
```
--------------------------------
### Custom Component Definition Example
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/README.md
Illustrates how to define custom components for specific data types using customNodeDefinitions. This example shows a DatePickerComponent for fields ending with '_date'.
```typescript
const dateDef = {
condition: ({ key }) => key.endsWith('_date'),
element: DatePickerComponent,
defaultValue: new Date().toISOString(),
showInTypesSelector: true,
name: 'Date'
}
```
--------------------------------
### FilterFunction Examples
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/README.md
Examples of FilterFunction implementations to restrict actions like editing, deleting, or dragging nodes based on their properties.
```typescript
type FilterFunction = (input: NodeData) => boolean
// Examples
restrictEdit: ({ level }) => level === 0 // Can't edit root
restrictDelete: ({ key }) => key === 'id' // Can't delete id
restrictDrag: ({ size }) => size !== null // Can't drag collections
collapse: ({ level, value }) => level > 2 // Collapse deep nesting
```
--------------------------------
### CSS Example: Override Specific Classes
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/api-reference/themes.md
Demonstrates how to override the default styles for specific elements like property keys and string input fields using CSS.
```css
/* Override specific class */
.jer-property-key {
color: #0066cc;
font-weight: bold;
}
.jer-input-string {
background-color: #f0f0f0;
border: 2px solid #0066cc;
border-radius: 4px;
}
/* Target nested levels */
.jer-collection .jer-collection .jer-property-key {
font-size: 0.9em;
}
```
--------------------------------
### TypeScript Example: Scale Entire Component
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/api-reference/themes.md
Shows how to scale the entire JsonEditor component by setting the rootFontSize prop. This affects all internal dimensions which use 'em' units.
```typescript
// Scale entire component
```
--------------------------------
### Dark Mode Theme Example
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/README.md
Illustrates how to apply custom themes to JsonEditor, including switching between light and dark themes based on an isDark variable.
```typescript
import { githubDarkTheme, githubLightTheme } from 'json-edit-react'
const theme = isDark ? githubDarkTheme : githubLightTheme
```
--------------------------------
### Match Node Value Example
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/api-reference/helpers.md
Use `matchNode` within a custom search filter to match a node's value against a search string. This example demonstrates matching both the node's value and its key.
```typescript
import { JsonEditor, matchNode } from 'json-edit-react'
const customSearchFilter = ({ value, key }, searchText) => {
// Match both the value and the key
return matchNode({ value }, searchText) || matchNode({ value: key }, searchText)
}
```
--------------------------------
### EnumDefinition Usage Example
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/types.md
Demonstrates how to define and use an EnumDefinition to restrict type selection in the JsonEditor.
```typescript
const colorEnum: EnumDefinition = {
enum: 'Color',
values: ['red', 'green', 'blue', 'yellow'],
matchPriority: 1
}
```
--------------------------------
### Custom Search Logic
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/configuration.md
Implement advanced search capabilities with a custom search function. This example demonstrates matching nested usernames and email domains.
```typescript
const advancedSearch = ({ key, value, path }, searchText) => {
// Match nested usernames in user objects
if (key === 'username') {
return value.includes(searchText)
}
// Match email domains
if (key === 'email' && value.includes('@')) {
return value.split('@')[1].includes(searchText)
}
return false
}
```
--------------------------------
### UpdateFunction Usage Example
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/types.md
Demonstrates how to implement the `UpdateFunction` callback to perform custom validation and data manipulation, such as enforcing positive values or truncating strings.
```typescript
const handleUpdate: UpdateFunction = ({ newData, newValue, path }) => {
if (newValue < 0) return 'Value must be positive'
if (typeof newValue === 'string' && newValue.length > 100) {
return ['value', newValue.slice(0, 100)] // Truncate
}
return true // Allow update
}
```
--------------------------------
### Example SearchFilterFunction for Matching Usernames
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/types.md
Illustrates using SearchFilterFunction to filter nodes, specifically matching usernames within user objects.
```typescript
const customSearch: SearchFilterFunction = ({ value, key }, searchText) => {
// Match usernames in a list of user objects
if (typeof value === 'object' && 'username' in value) {
return value.username.includes(searchText)
}
return false
}
```
--------------------------------
### TypeScript Example: Accessible Theme
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/api-reference/themes.md
Defines a theme object with styles designed for accessibility, focusing on high contrast for text and background colors.
```typescript
const accessibleTheme = {
styles: {
property: '#1a1a1a', // High contrast dark text
string: '#c1272d', // High contrast red
number: '#006bb6', // High contrast blue
container: { backgroundColor: '#ffffff' }
}
}
```
--------------------------------
### TypeScript Example: Icon Customization
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/api-reference/themes.md
Shows how to replace default icons (add, edit, delete) in the JsonEditor component with custom icons from a library like 'react-icons'.
```typescript
import { JsonEditor, githubDarkTheme } from 'json-edit-react'
import { FiPlus, FiEdit2, FiTrash2 } from 'react-icons/fi'
,
edit: ,
delete:
}}
/>
```
--------------------------------
### Customizing Confirm Action Keyboard Shortcut
Source: https://github.com/carlosnz/json-edit-react/blob/main/README.md
Example of overriding the default 'confirm' keyboard action to use a combination of keys, such as 'Cmd-Enter' or 'Ctrl-Enter'.
```typescript
keyboardControls = {
confirm: {
key: "Enter",
modifier: [ "Meta", "Control" ]
}
}
```
--------------------------------
### TypeScript Example: Dark Mode Detection
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/api-reference/themes.md
Implements dark mode detection using the 'prefers-color-scheme' media query and applies the appropriate theme (githubDarkTheme or githubLightTheme) to the JsonEditor component.
```typescript
import { useEffect, useState } from 'react'
import { JsonEditor, githubDarkTheme, githubLightTheme } from 'json-edit-react'
const MyEditor = ({ data }) => {
const [isDark, setIsDark] = useState(false)
useEffect(() => {
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
setIsDark(mediaQuery.matches)
const handler = (e) => setIsDark(e.matches)
mediaQuery.addEventListener('change', handler)
return () => mediaQuery.removeEventListener('change', handler)
}, [])
return (
)
}
```
--------------------------------
### Convert Path to String Example
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/api-reference/helpers.md
Demonstrates converting a path array into a dot-notation string using `toPathString`. This is useful for generating unique IDs or references for nodes.
```typescript
import { toPathString } from 'json-edit-react'
toPathString(['user', 'profile', 'name'])
// Output: 'user.profile.name'
toPathString(['items', 0, 'title'])
// Output: 'items.0.title'
toPathString(['data', '', 'value'])
// Output: 'data..value'
// (Empty string keys use a non-printable character internally)
```
--------------------------------
### Match Node Key Example
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/api-reference/helpers.md
Use `matchNodeKey` as a search filter to specifically match a node's key or any part of its path against a search string.
```typescript
import { JsonEditor, matchNodeKey } from 'json-edit-react'
```
--------------------------------
### TypeScript Example: Color Independence (Bad Practice)
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/api-reference/themes.md
Shows a bad practice for theme styling where only color is used to differentiate elements, which can be problematic for users with color vision deficiencies.
```typescript
// BAD: Only color difference
const badTheme = {
styles: {
readonlyProp: 'gray',
editableProp: 'black'
}
}
```
--------------------------------
### Controlled State Example
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/README.md
Demonstrates how to use the JsonEditor in a controlled state pattern, where the component's state is managed externally using useState and passed via props.
```typescript
const [data, setData] = useState(initialData)
{
// Side effect: save to API
await api.save(newData)
return true
}}
/>
```
--------------------------------
### Custom Keyboard Controls: Override Confirm Key
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/configuration.md
Example of overriding a specific keyboard control, in this case, the confirm key, to use a modifier combination.
```jsx
```
--------------------------------
### Restrict Editing Example
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/README.md
Demonstrates how to restrict editing, deletion, and addition of properties in JsonEditor using the restrictEdit, restrictDelete, and restrictAdd props with filter functions.
```typescript
{
return level === 0 || ['id', 'created_at'].includes(String(key))
}}
restrictDelete={({ size }) => size !== null} // Can't delete collections
restrictAdd={({ key }) => key === 'users'} // Can't add to users
/>
```
--------------------------------
### Custom Search Filter Example
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/README.md
Shows how to implement custom search logic for JsonEditor by providing a searchFilter function that determines if a node's value matches the search text.
```typescript
const searchFn = ({ value, key, path }, searchText) => {
// Custom search logic
return String(value).toLowerCase().includes(searchText.toLowerCase())
}
```
--------------------------------
### JSON Schema Validation Setup
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/configuration.md
Integrate JSON schema validation using Ajv. The onUpdate callback checks the new data against the schema and returns an error message if invalid.
```typescript
import Ajv from 'ajv'
import schema from './schema.json'
const ajv = new Ajv()
const validate = ajv.compile(schema)
{
if (!validate(newData)) {
const msg = validate.errors?.[0]?.message ?? 'Invalid data'
return `Schema error: ${msg}`
}
return true
}}
/>
```
--------------------------------
### Configure Node Collapse Behavior
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/api-reference/JsonEditor.md
Control the initial collapsed state of nodes using boolean values, depth levels, or custom logic functions. Use `collapse = true` to start all nodes closed, `collapse = false` for all nodes open (default), or specify a depth level. A custom function allows fine-grained control based on node properties.
```typescript
collapse = true // All nodes start closed
collapse = false // All nodes start open (default)
collapse = 2 // Nodes at depth > 2 start closed
collapse = ({ level, value, key }) => {
// Custom logic; return true to collapse this node
if (key === 'metadata') return true
if (level > 3) return true
return false
}
```
--------------------------------
### Launch Development App with Yarn
Source: https://github.com/carlosnz/json-edit-react/blob/main/custom-component-library/README.md
Run this command to launch the Vite development server for previewing and developing custom components.
```bash
yarn dev
```
--------------------------------
### JSON Schema Validation with Ajv
Source: https://github.com/carlosnz/json-edit-react/blob/main/README.md
Implement JSON Schema validation by creating an onUpdate function that passes data to Ajv. This example shows how to compile a schema, validate new data, log errors, and return a user-friendly error message.
```javascript
import { JsonEditor } from 'json-edit-react'
import Ajv from 'ajv'
import schema from './my-json-schema.json'
// Put these outside React components:
const ajv = new Ajv()
const validate = ajv.compile(schema)
// Etc....
// In the React component:
return
{
const valid = validate(newData)
if (!valid) {
console.log('Errors', validate.errors)
const errorMessage = validate.errors
?.map((error) => `${error.instancePath}${error.instancePath ? ': '
: ''}${error.message}`)
.join('\n')
// Send detailed error message to an external UI element,
// such as a "Toast" notification
displayError({
title: 'Not compliant with JSON Schema',
description: errorMessage,
status: 'error',
})
// This string returned to and displayed in json-edit-react UI
return 'JSON Schema error'
}
}}
{ ...otherProps } />
```
--------------------------------
### Common Commands for json-edit-react
Source: https://github.com/carlosnz/json-edit-react/blob/main/CLAUDE.md
These commands are used for setting up the project, running the demo, testing, linting, and building the library. They are typically run from the repository root using Yarn.
```sh
yarn setup
yarn dev
yarn demo
yarn demo:package
yarn test
yarn lint
yarn compile
yarn build
yarn release
```
--------------------------------
### Using a Built-in Theme
Source: https://github.com/carlosnz/json-edit-react/blob/main/README.md
Import a theme from the package and pass it to the theme prop to apply a predefined style. This is useful for quickly applying a consistent look.
```javascript
import { JsonEditor, githubDarkTheme } from 'json-edit-react'
// ...other imports
const MyApp = () => {
const [ data, setData ] = useState({ one: 1, two: 2 })
return
}
```
--------------------------------
### Basic JsonEditor Usage
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/api-reference/JsonEditor.md
Demonstrates how to use the JsonEditor component with basic data binding and an update handler. It also shows how to restrict deletion of the root node and apply a simple theme.
```typescript
import React, { useState } from 'react'
import { JsonEditor } from 'json-edit-react'
const MyApp = () => {
const [data, setData] = useState({
name: 'John',
age: 30,
hobbies: ['reading', 'gaming']
})
const handleUpdate = ({ newData, path, newValue, name }) => {
console.log(`Updated ${name} at path ${path.join('.')}: ${newValue}`)
// Return nothing to allow the update, or string for error message
}
return (
level === 0} // Can't delete root
theme={{ styles: { property: '#333' } }}
/>
)
}
export default MyApp
```
--------------------------------
### Check if Value is Collection Example
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/api-reference/helpers.md
Use `isCollection` as a type guard in a custom `restrictEdit` function to determine if a value is an object or array. This example restricts editing of non-empty collections.
```typescript
import { isCollection } from 'json-edit-react'
const handleRestriction = ({ value }) => {
// Restrict editing of non-empty collections
if (isCollection(value) && Object.keys(value).length > 0) {
return true // Restrict
}
return false // Allow
}
```
--------------------------------
### Import Custom Components and Hooks
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/README.md
Import pre-built custom components like LinkCustomComponent and StringEdit, as well as the useKeyboardListener hook.
```typescript
import {
LinkCustomComponent,
LinkCustomNodeDefinition,
StringDisplay,
StringEdit,
useKeyboardListener
} from 'json-edit-react'
```
--------------------------------
### Custom Search Filter Function Example
Source: https://github.com/carlosnz/json-edit-react/blob/main/README.md
This example demonstrates a custom search function for json-edit-react. It matches nodes based on 'name' or 'username' properties within a specific data structure, making the entire 'Client' object visible if a match is found. This is useful for finding and editing specific user details.
```javascript
({ path, fullData }, searchText) => {
// Matches *any* node that shares a path (i.e. a descendent) with a matching name/username
if (path?.length >= 2) {
const index = path?.[0]
return (
matchNode({ value: fullData[index].name }, searchText) ||
matchNode({ value: fullData[index].username }, searchText)
)
} else return false
}
```
--------------------------------
### Usage of IconAdd Component
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/api-reference/icons-components.md
Demonstrates how to use the IconAdd component in a React application.
```typescript
import { IconAdd } from 'json-edit-react'
```
--------------------------------
### Usage of IconOk Component
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/api-reference/icons-components.md
Demonstrates how to use the IconOk component in a React application.
```typescript
import { IconOk } from 'json-edit-react'
```
--------------------------------
### Allow Specific Types
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/configuration.md
Configure restrictTypeSelection to limit the allowed data types for nodes. This example permits only 'string' and 'number'.
```typescript
restrictTypeSelection = ['string', 'number']
```
--------------------------------
### Import and Use LinkCustomNodeDefinition
Source: https://github.com/carlosnz/json-edit-react/blob/main/README.md
Import the LinkCustomNodeDefinition and include it in your customNodeDefinitions prop to enable clickable hyperlinks for URL strings.
```javascript
import { JsonEditor, LinkCustomNodeDefinition } from 'json-edit-react'
// ...Other stuff
return (
)
```
--------------------------------
### Enum Definition Example
Source: https://github.com/carlosnz/json-edit-react/blob/main/README.md
Defines an Enum type with a name, allowed values, and an optional match priority for initial value recognition.
```javascript
{
enum: "My Enum Type" // name that will appear in the Types selector drop-down
values: [
"Option A",
"Option B",
"Option C"
]
matchPriority: 1 // (Optional) used to recognize existing string values
// as the particular type (see below)
}
```
--------------------------------
### Integration Notes
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/api-reference/JsonEditor.md
Provides guidance on integrating JsonEditor with external systems, covering state management, error handling, performance considerations, and asynchronous updates.
```APIDOC
## Integration Notes
### State Management
- Pass both `data` and `setData` for controlled updates.
- The component can manage state internally if `setData` is omitted, but this is not recommended.
### Error Handling
- Use the `onError` callback for custom error UI instead of relying on built-in error messages.
- Set `showErrorMessages = false` when using a custom `onError` callback.
### Performance
- The component recursively renders all visible nodes.
- For very large datasets, use `searchText`/`searchFilter` to reduce visible nodes.
### Async Updates
- `onUpdate`/`onEdit`/`onDelete`/`onAdd` can return Promises for async validation (e.g., API calls, schema validation).
```
--------------------------------
### Example FilterFunction for Restricting Edits
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/types.md
Demonstrates how to use FilterFunction to conditionally restrict editing of nodes based on their key, level, or value.
```typescript
const restrictEdit: FilterFunction = ({ key, level, value }) => {
if (level === 0) return true // Restrict root
if (key === 'id') return true // Restrict id fields
if (isCollection(value) && Object.keys(value).length === 0) return false // Allow empty
return false
}
```
--------------------------------
### Basic Implementation
Source: https://github.com/carlosnz/json-edit-react/blob/main/README.md
Import and use the JsonEditor component in your React application. The `data` prop is required, and `setData` is recommended for updating the data.
```jsx
import { JsonEditor } from 'json-edit-react'
// In your React component:
return (
);
```
--------------------------------
### Restrict Editing by Key
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/configuration.md
Use the restrictEdit function to specify which keys are editable. This example prevents editing of 'public' and 'shared' keys.
```typescript
restrictEdit = ({ key }) => key !== 'public' && key !== 'shared'
```
--------------------------------
### Usage of IconChevron Component
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/api-reference/icons-components.md
Demonstrates how to use the IconChevron component in a React application.
```typescript
import { IconChevron } from 'json-edit-react'
```
--------------------------------
### Apply GitHub Light Theme to JsonEditor
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/api-reference/themes.md
Use the githubLightTheme for a clean, minimal, and professional look similar to GitHub's web UI. Pass this theme to the 'theme' prop.
```typescript
import { githubLightTheme } from 'json-edit-react'
```
--------------------------------
### Styling Themeable Elements with String Values
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/api-reference/themes.md
Demonstrates how to apply simple color strings to themeable elements like 'property', 'string', and 'boolean'. These are interpreted as foreground or background colors.
```typescript
const theme = {
styles: {
property: '#333333', // Dark gray text
string: 'rgb(203, 75, 22)', // Orange
boolean: 'green', // Color name
}
}
```
--------------------------------
### Replacing Built-in Icons
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/api-reference/icons-components.md
Replace default icons with custom components using the 'icons' prop on JsonEditor. This example uses icons from 'react-icons/fi'.
```typescript
import { JsonEditor } from 'json-edit-react'
import { FiPlus, FiEdit2, FiTrash2, FiCopy, FiCheck, FiX, FiChevronDown } from 'react-icons/fi'
,
edit: ,
delete: ,
copy: ,
ok: ,
cancel: ,
chevron:
}}
/>
```
--------------------------------
### OnEditEventFunction Type
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/types.md
Callback function type for when a user starts or stops editing a node. It provides the path to the node and whether it's a key.
```typescript
type OnEditEventFunction = (
path: (CollectionKey | null)[] | null,
isKey: boolean
) => void
```
--------------------------------
### Replacing Icons
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/api-reference/icons-components.md
Demonstrates how to replace built-in icons with custom components using the `icons` prop on the `JsonEditor` component.
```APIDOC
## Replacing Icons
To replace built-in icons with your own components, use the `icons` prop on `JsonEditor`:
```typescript
import { JsonEditor } from 'json-edit-react'
import { FiPlus, FiEdit2, FiTrash2, FiCopy, FiCheck, FiX, FiChevronDown } from 'react-icons/fi'
,
edit: ,
delete: ,
copy: ,
ok: ,
cancel: ,
chevron:
}}
/>
```
```
--------------------------------
### Restrict Deletion of Objects and Arrays
Source: https://github.com/carlosnz/json-edit-react/blob/main/README.md
Control deletion permissions by using a FilterFunction with restrictDelete. This example allows deletion only for non-collection nodes (where 'size' is null).
```javascript
restrictDelete = { ({ size }) => size !== null }
```
--------------------------------
### Custom Keyboard Controls: Different Modifiers
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/configuration.md
Demonstrates how to use different modifiers for specific keyboard actions, such as clipboard operations and collapse toggling.
```jsx
```
--------------------------------
### Usage of IconCopy Component
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/api-reference/icons-components.md
Demonstrates how to use the IconCopy component in a React application.
```typescript
import { IconCopy } from 'json-edit-react'
```
--------------------------------
### Restrict Drag by Condition
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/configuration.md
Implement custom logic for restrictDrag to conditionally disable dragging. This example prevents moving 'settings' keys and primitive values.
```typescript
restrictDrag = ({ key, size }) => {
if (key === 'settings') return true // Can't move settings
if (size === null) return true // Can't drag primitive values
return false
}
```
--------------------------------
### Import Theme Definitions
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/README.md
Import various theme definitions for styling the JsonEditor component.
```typescript
import {
defaultTheme,
githubDarkTheme,
githubLightTheme,
monoDarkTheme,
monoLightTheme,
candyWrapperTheme,
psychedelicTheme
} from 'json-edit-react'
```
--------------------------------
### Copy Function Input Structure
Source: https://github.com/carlosnz/json-edit-react/blob/main/README.md
The copy callback provides details about the item copied to the clipboard. It includes the key, path, value, type of copy action, stringified value, and success status.
```json
{
key,
path,
value,
type,
stringValue,
success,
errorMessage
}
```
--------------------------------
### Multiple Overrides for Theming
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/api-reference/themes.md
Apply multiple layers of theme overrides by passing an array of theme objects. Styles are applied sequentially, with later objects overriding earlier ones.
```jsx
const baseStyles = { styles: { container: { fontSize: '14px' } } }
const colorOverrides = { styles: { string: 'purple' } }
const iconOverrides = { styles: { iconEdit: '#0099ff' } }
```
--------------------------------
### Conditional Theming
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/api-reference/themes.md
Implement conditional theming by dynamically selecting theme configurations based on application state, such as dark mode preference.
```jsx
const theme = isDarkMode
? [githubDarkTheme, customDarkOverrides]
: [githubLightTheme, customLightOverrides]
```
--------------------------------
### Displaying Array Indices
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/api-reference/JsonEditor.md
Control whether array indices are displayed as keys using 'showArrayIndices'. Set 'arrayIndexFromOne' to true to start indices from 1.
```typescript
```
--------------------------------
### Example TypeFilterFunction for Restricting Type Selection
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/types.md
Shows how to use TypeFilterFunction to dynamically restrict the available data types for a node based on its key or current value.
```typescript
const restrictTypes: TypeFilterFunction = ({ key, value }) => {
if (key === 'status') return ['string'] // Only string
if (typeof value === 'boolean') return false // Type cannot change
return ['string', 'number', 'boolean'] // Default options
}
```
--------------------------------
### Type Restrictions with Enums
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/configuration.md
Combine standard types with custom enum values for type selection. This example includes 'active', 'inactive', and 'pending' for a 'Status' enum.
```typescript
restrictTypeSelection = [
'string', 'number', 'boolean',
{
enum: 'Status',
values: ['active', 'inactive', 'pending'],
matchPriority: 1
}
]
```
--------------------------------
### Use Built-in Themes
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/configuration.md
Import and apply pre-defined themes like githubDarkTheme or monoLightTheme directly to the JsonEditor component.
```typescript
import { JsonEditor, githubDarkTheme, monoLightTheme } from 'json-edit-react'
```
--------------------------------
### Restrict Editing by Depth
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/configuration.md
Limit editing capabilities based on the nesting level of the JSON data. This example only allows editing at the root level (level 0).
```typescript
restrictEdit = ({ level }) => level === 0 // Can't edit root
```
--------------------------------
### Usage of IconEdit Component
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/api-reference/icons-components.md
Demonstrates how to use the IconEdit component in a React application.
```typescript
import { IconEdit } from 'json-edit-react'
```
--------------------------------
### Dynamic Type Restrictions
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/configuration.md
Dynamically determine allowed types based on the key and current value. This example restricts 'status' to strings and prevents type changes for booleans.
```typescript
restrictTypeSelection = ({ key, value }) => {
if (key === 'status') return ['string']
if (typeof value === 'boolean') return false // Can't change type
return ['string', 'number', 'null']
}
```
--------------------------------
### Apply Mono Light Theme to JsonEditor
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/api-reference/themes.md
Use the monoLightTheme for a grayscale theme on a light background, providing accessibility and a professional appearance suitable for print.
```typescript
import { monoLightTheme } from 'json-edit-react'
```
--------------------------------
### Import Default and Other Themes
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/api-reference/themes.md
Import necessary themes from the 'json-edit-react' library. This is typically done at the top of your component file.
```typescript
import { defaultTheme, githubDarkTheme, monoLightTheme, ... } from 'json-edit-react'
```
--------------------------------
### Simple Search Configuration
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/configuration.md
Configure basic search functionality by providing a searchText string and optionally a searchFilter to target values only.
```typescript
```
--------------------------------
### Usage of IconCancel Component
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/api-reference/icons-components.md
Demonstrates how to use the IconCancel component in a React application.
```typescript
import { IconCancel } from 'json-edit-react'
```
--------------------------------
### Restrict 'age' input to positive values up to 100
Source: https://github.com/carlosnz/json-edit-react/blob/main/README.md
Use the onChange callback to validate and constrain numeric input. This example limits the 'age' field to values between 0 and 100.
```javascript
onChange = ({ newValue, name }) => {
if (name === "age" && newValue < 0) return 0;
if (name === "age" && newValue > 100) return 100;
return newValue
}
```
--------------------------------
### Importing Icon Components
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/api-reference/icons-components.md
Import individual icon components from the 'json-edit-react' library.
```typescript
import { IconAdd, IconEdit, ... } from 'json-edit-react'
```
--------------------------------
### Theme Styling with Functions
Source: https://github.com/carlosnz/json-edit-react/blob/main/_autodocs/configuration.md
Apply context-dependent styling using theme functions that receive key, level, and value as arguments. This allows dynamic style adjustments.
```typescript
{
if (key === 'secret') return { color: 'red', fontWeight: 'bold' }
if (level > 2) return { opacity: 0.7 }
return null // Use default
}
}
}}
/>
```
--------------------------------
### Restrict Node Type to a Specific Enum
Source: https://github.com/carlosnz/json-edit-react/blob/main/README.md
This example restricts the node type selection to a single enum ('Eye colour') when the key matches 'eye_color'. If the key does not match, all types are allowed.
```javascript
restrictTypeSelection = ({ key }) => {
if (key === 'eye_color')
return [
// Only one type returned, so can't be changed to another type
{
enum: 'Eye colour',
values: ['blue', 'brown', 'green', 'hazel'],
matchPriority: 1,
},
]
return true // No other node types can be changed either
}
```