or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/npm-react-json-view

Interactive react component for displaying javascript arrays and JSON objects.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/react-json-view@1.21.x

To install, run

npx @tessl/cli install tessl/npm-react-json-view@1.21.0

0

# React JSON View

1

2

React JSON View is an interactive React component for displaying and editing JavaScript arrays and JSON objects with a responsive, customizable interface. It provides extensive theming options, in-place editing capabilities, and comprehensive data type support.

3

4

## Package Information

5

6

- **Package Name**: react-json-view

7

- **Package Type**: npm

8

- **Language**: JavaScript/TypeScript

9

- **Installation**: `npm install react-json-view`

10

11

## Core Imports

12

13

```typescript

14

import ReactJson from "react-json-view";

15

```

16

17

CommonJS:

18

19

```javascript

20

const ReactJson = require("react-json-view");

21

```

22

23

## Basic Usage

24

25

```typescript

26

import ReactJson from "react-json-view";

27

28

// Basic JSON display

29

const myJsonObject = {

30

users: [

31

{ id: 1, name: "Alice", active: true },

32

{ id: 2, name: "Bob", active: false }

33

],

34

metadata: {

35

total: 2,

36

lastUpdated: "2023-01-01"

37

}

38

};

39

40

function App() {

41

return <ReactJson src={myJsonObject} />;

42

}

43

```

44

45

## Capabilities

46

47

### Core Component

48

49

The main ReactJsonView component with comprehensive display and interaction options.

50

51

```typescript { .api }

52

interface ReactJsonViewProps {

53

/** The input JSON object or array to display (required) */

54

src: object;

55

56

/** Name of the root node. Use null or false for no name (default: "root") */

57

name?: string | null | false;

58

59

/** Base-16 theme name or custom theme object (default: "rjv-default") */

60

theme?: ThemeKeys | ThemeObject;

61

62

/** Custom CSS styles for container (default: {}) */

63

style?: React.CSSProperties;

64

65

/** Style of expand/collapse icons (default: "triangle") */

66

iconStyle?: 'circle' | 'triangle' | 'square';

67

68

/** Indent width for nested objects (default: 4) */

69

indentWidth?: number;

70

71

/** Collapse all nodes (true) or at specific depth (number) (default: false) */

72

collapsed?: boolean | number;

73

74

/** Truncate strings after specified length (default: false) */

75

collapseStringsAfterLength?: number | false;

76

77

/** Custom collapse logic callback (default: false) */

78

shouldCollapse?: false | ((field: CollapsedFieldProps) => boolean);

79

80

/** Group arrays after specified length (default: 100) */

81

groupArraysAfterLength?: number;

82

83

/** Enable copy functionality or provide custom copy callback (default: true) */

84

enableClipboard?: boolean | ((copy: OnCopyProps) => void);

85

86

/** Show object/array sizes (default: true) */

87

displayObjectSize?: boolean;

88

89

/** Show data type labels (default: true) */

90

displayDataTypes?: boolean;

91

92

/** Show array indices as prefixes for array elements (default: true) */

93

displayArrayKey?: boolean;

94

95

/** Show quotes on object keys (default: true) */

96

quotesOnKeys?: boolean;

97

98

/** Sort object keys alphabetically (default: false) */

99

sortKeys?: boolean;

100

101

/** Show array indices as prefixes for array elements (default: true) */

102

displayArrayKey?: boolean;

103

104

/** Edit callback - enables edit functionality when provided (default: false) */

105

onEdit?: ((edit: InteractionProps) => false | any) | false;

106

107

/** Add callback - enables add functionality when provided (default: false) */

108

onAdd?: ((add: InteractionProps) => false | any) | false;

109

110

/** Delete callback - enables delete functionality when provided (default: false) */

111

onDelete?: ((del: InteractionProps) => false | any) | false;

112

113

/** Select callback - triggered when clicking values (default: false) */

114

onSelect?: ((select: OnSelectProps) => void) | false;

115

116

/** Default value for new keys when adding (default: null) */

117

defaultValue?: TypeDefaultValue | TypeDefaultValue[] | null;

118

119

/** Custom validation error message (default: "Validation Error") */

120

validationMessage?: string;

121

}

122

123

declare const ReactJson: React.ComponentType<ReactJsonViewProps>;

124

export default ReactJson;

125

```

126

127

**Usage Examples:**

128

129

```typescript

130

import ReactJson from "react-json-view";

131

132

// Themed display with editing

133

function JsonEditor() {

134

const [data, setData] = useState({

135

name: "John",

136

age: 30,

137

hobbies: ["reading", "coding"]

138

});

139

140

return (

141

<ReactJson

142

src={data}

143

theme="monokai"

144

collapsed={1}

145

displayDataTypes={false}

146

onEdit={(edit) => {

147

setData(edit.updated_src);

148

}}

149

onAdd={(add) => {

150

setData(add.updated_src);

151

}}

152

onDelete={(del) => {

153

setData(del.updated_src);

154

}}

155

/>

156

);

157

}

158

159

// Read-only display with custom styling

160

function JsonDisplay() {

161

return (

162

<ReactJson

163

src={complexData}

164

name="API Response"

165

theme="solarized"

166

collapsed={2}

167

collapseStringsAfterLength={50}

168

groupArraysAfterLength={10}

169

style={{

170

backgroundColor: "#f5f5f5",

171

borderRadius: "4px",

172

padding: "10px"

173

}}

174

/>

175

);

176

}

177

```

178

179

### Theme System

180

181

React JSON View supports extensive theming through built-in base-16 themes or custom theme objects.

182

183

```typescript { .api }

184

/** Built-in theme names */

185

type ThemeKeys =

186

| 'apathy' | 'apathy:inverted'

187

| 'ashes' | 'bespin' | 'brewer'

188

| 'bright' | 'bright:inverted'

189

| 'chalk' | 'codeschool' | 'colors'

190

| 'eighties' | 'embers' | 'flat'

191

| 'google' | 'grayscale' | 'grayscale:inverted'

192

| 'greenscreen' | 'harmonic' | 'hopscotch'

193

| 'isotope' | 'marrakesh' | 'mocha'

194

| 'monokai' | 'ocean' | 'paraiso'

195

| 'pop' | 'railscasts' | 'rjv-default'

196

| 'shapeshifter' | 'shapeshifter:inverted'

197

| 'solarized' | 'summerfruit' | 'summerfruit:inverted'

198

| 'threezerotwofour' | 'tomorrow' | 'tube' | 'twilight';

199

200

/** Custom theme object following base-16 specification */

201

interface ThemeObject {

202

base00: string; // Default Background

203

base01: string; // Lighter Background

204

base02: string; // Selection Background

205

base03: string; // Comments, Invisibles

206

base04: string; // Dark Foreground

207

base05: string; // Default Foreground

208

base06: string; // Light Foreground

209

base07: string; // Light Background

210

base08: string; // Variables, Tags, Delimiters

211

base09: string; // Integers, Boolean, Constants

212

base0A: string; // Classes, Markup Bold

213

base0B: string; // Strings, Inherited Class

214

base0C: string; // Support, Regular Expressions

215

base0D: string; // Functions, Methods, Headings

216

base0E: string; // Keywords, Storage, Selector

217

base0F: string; // Deprecated, Opening/Closing Tags

218

}

219

```

220

221

**Usage Examples:**

222

223

```typescript

224

// Using built-in themes

225

<ReactJson src={data} theme="monokai" />

226

<ReactJson src={data} theme="solarized" />

227

<ReactJson src={data} theme="grayscale:inverted" />

228

229

// Custom theme

230

const customTheme: ThemeObject = {

231

base00: "#ffffff",

232

base01: "#f5f5f5",

233

base02: "#e0e0e0",

234

base03: "#888888",

235

base04: "#666666",

236

base05: "#333333",

237

base06: "#111111",

238

base07: "#000000",

239

base08: "#d32f2f",

240

base09: "#f57c00",

241

base0A: "#fbc02d",

242

base0B: "#388e3c",

243

base0C: "#0097a7",

244

base0D: "#1976d2",

245

base0E: "#7b1fa2",

246

base0F: "#5d4037"

247

};

248

249

<ReactJson src={data} theme={customTheme} />

250

```

251

252

### Interaction Callbacks

253

254

Enable editing, adding, and deleting functionality through callback props.

255

256

```typescript { .api }

257

/** Interaction event data passed to callbacks */

258

interface InteractionProps {

259

/** Updated JSON tree after the interaction */

260

updated_src: object;

261

/** Original JSON tree before the interaction */

262

existing_src: object;

263

/** Key name of the interacted element */

264

name: string | null;

265

/** Array of keys representing the path to the element */

266

namespace: Array<string | null>;

267

/** Original value before interaction */

268

existing_value: object | string | number | boolean | null;

269

/** New value after interaction */

270

new_value?: object | string | number | boolean | null;

271

}

272

273

/** Selection event data */

274

interface OnSelectProps {

275

/** Name of the selected element */

276

name: string | null;

277

/** Value of the selected element */

278

value: object | string | number | boolean | null;

279

/** Type of the value (refined for numbers: 'float', 'integer', 'nan') */

280

type: string;

281

/** Array of keys representing the path to the selected element */

282

namespace: Array<string | null>;

283

}

284

285

/** Copy event data */

286

interface OnCopyProps {

287

/** The JSON tree source object */

288

src: object;

289

/** Array of keys representing the path to copied element */

290

namespace: Array<string | null>;

291

/** Name of the copied element */

292

name: string | null;

293

}

294

```

295

296

**Usage Examples:**

297

298

```typescript

299

function EditableJson() {

300

const [jsonData, setJsonData] = useState({

301

users: [{ name: "Alice" }],

302

settings: { theme: "light" }

303

});

304

305

const handleEdit = (edit: InteractionProps) => {

306

console.log("Editing:", edit.name, "from", edit.existing_value, "to", edit.new_value);

307

308

// Validate the change

309

if (edit.name === "theme" && !["light", "dark"].includes(edit.new_value as string)) {

310

return false; // Prevent invalid theme

311

}

312

313

// Accept the change

314

setJsonData(edit.updated_src);

315

};

316

317

const handleAdd = (add: InteractionProps) => {

318

console.log("Adding:", add.name, "=", add.new_value);

319

setJsonData(add.updated_src);

320

};

321

322

const handleDelete = (del: InteractionProps) => {

323

console.log("Deleting:", del.name);

324

325

// Prevent deletion of required fields

326

if (del.name === "users") {

327

return false;

328

}

329

330

setJsonData(del.updated_src);

331

};

332

333

const handleSelect = (selection: OnSelectProps) => {

334

console.log("Selected:", selection.name, "=", selection.value);

335

console.log("Path:", selection.namespace.join("."));

336

};

337

338

return (

339

<ReactJson

340

src={jsonData}

341

onEdit={handleEdit}

342

onAdd={handleAdd}

343

onDelete={handleDelete}

344

onSelect={handleSelect}

345

defaultValue="New Value"

346

validationMessage="Invalid input - please check your data"

347

/>

348

);

349

}

350

```

351

352

### Display Configuration

353

354

Fine-tune the appearance and behavior of the JSON display.

355

356

```typescript { .api }

357

/** Collapse behavior configuration */

358

interface CollapsedFieldProps {

359

/** Name of the field being evaluated for collapse */

360

name: string | null;

361

/** The corresponding JSON subtree */

362

src: object;

363

/** Type of the source ('array' or 'object') */

364

type: 'array' | 'object';

365

/** Array representing the scope path */

366

namespace: Array<string | null>;

367

}

368

369

/** Valid types for default values when adding new elements */

370

type TypeDefaultValue = string | number | boolean | object;

371

```

372

373

**Usage Examples:**

374

375

```typescript

376

// Advanced display configuration

377

<ReactJson

378

src={largeDataset}

379

name="Dataset"

380

collapsed={(field) => {

381

// Collapse arrays with more than 5 items

382

if (field.type === "array" && field.src.length > 5) {

383

return true;

384

}

385

// Collapse nested objects deeper than 2 levels

386

return field.namespace.length > 2;

387

}}

388

collapseStringsAfterLength={100}

389

groupArraysAfterLength={20}

390

displayObjectSize={true}

391

displayDataTypes={true}

392

displayArrayKey={true}

393

quotesOnKeys={false}

394

sortKeys={true}

395

indentWidth={2}

396

iconStyle="square"

397

/>

398

399

// Minimal clean display

400

<ReactJson

401

src={data}

402

name={false}

403

displayObjectSize={false}

404

displayDataTypes={false}

405

displayArrayKey={false}

406

quotesOnKeys={false}

407

enableClipboard={false}

408

style={{

409

fontFamily: "Monaco, monospace",

410

fontSize: "14px"

411

}}

412

/>

413

```

414

415

### Clipboard Integration

416

417

Configure copy-to-clipboard functionality with optional custom handling.

418

419

**Usage Examples:**

420

421

```typescript

422

// Enable clipboard with custom handler

423

<ReactJson

424

src={data}

425

enableClipboard={(copy: OnCopyProps) => {

426

const value = copy.namespace.reduce(

427

(obj, key) => key ? obj[key] : obj,

428

copy.src

429

);

430

431

// Custom copy logic

432

navigator.clipboard.writeText(JSON.stringify(value, null, 2));

433

console.log("Copied to clipboard:", copy.name);

434

}}

435

/>

436

437

// Simple clipboard enable/disable

438

<ReactJson src={data} enableClipboard={true} />

439

<ReactJson src={data} enableClipboard={false} />

440

```

441

442

## Error Handling

443

444

React JSON View includes built-in validation and error handling:

445

446

- **Invalid src prop**: Component displays error message if `src` is not an object or array

447

- **Invalid theme**: Falls back to "rjv-default" theme if custom theme is malformed

448

- **Callback validation**: Returning `false` from `onEdit`, `onAdd`, or `onDelete` prevents the change and shows validation message

449

- **Type safety**: TypeScript definitions help prevent common usage errors

450

451

```typescript

452

// Validation example

453

const handleEdit = (edit: InteractionProps) => {

454

try {

455

// Validate new value

456

if (typeof edit.new_value === 'string' && edit.new_value.length > 100) {

457

return false; // Shows validationMessage

458

}

459

460

setData(edit.updated_src);

461

} catch (error) {

462

console.error("Edit failed:", error);

463

return false;

464

}

465

};

466

467

<ReactJson

468

src={data}

469

onEdit={handleEdit}

470

validationMessage="Value too long (max 100 characters)"

471

/>

472

```