JSON Diff Patch for React
jsondiffpatch-react is a React component designed to visualize differences between two JavaScript objects or arrays, built upon the core `jsondiffpatch` library. The current stable version is 1.0.8, with recent minor updates indicating active maintenance rather than rapid feature development. It originated as a fork of the now-archived `jsondiffpatch-for-react` project. Its key differentiator is providing a readily available React component for rendering detailed, annotated JSON deltas in an HTML format, significantly simplifying the integration of JSON comparison UIs into React applications without needing to implement diff visualization from scratch. It offers configurable options such as showing or hiding unchanged values and enabling a custom `objectHash` function, which is particularly beneficial for optimizing array comparison, especially when dealing with lists of objects that may not have inherent stable unique identifiers.
Common errors
-
ReferenceError: React is not defined
cause The `React` object was not imported into the scope where JSX is being used.fixAdd `import React from 'react';` at the top of your component file. -
TypeError: Cannot read properties of undefined (reading 'map') OR TypeError: Cannot read properties of null (reading 'length')
cause The `left` or `right` props were not provided, or were `undefined`/`null`, leading to attempts to iterate or access properties on non-existent data within the component.fixAlways ensure that both `left` and `right` props are provided with valid JSON-serializable data (objects, arrays, strings). If an 'empty' state is intended, provide an empty object `{}` or array `[]` rather than `undefined` or `null` for better component stability. -
Incorrect diff output for arrays (e.g., items appear as deleted/added instead of modified)
cause When comparing arrays of objects, `jsondiffpatch` without an appropriate `objectHash` function may fail to correctly identify modified objects if they lack stable unique identifiers. It might treat them as entirely new objects being added and old ones being removed.fixImplement and pass an `objectHash` prop that provides a unique and consistent key for each object in your arrays. This helps `jsondiffpatch` track object identities across changes. For example: `<JsonDiffReact objectHash={(obj) => obj.id || JSON.stringify(obj)} />`.
Warnings
- gotcha The `objectHash` prop is crucial for accurate and performant array comparison when elements within arrays lack stable unique identifiers. Without it, `jsondiffpatch` might incorrectly identify moved or modified items as additions and deletions, leading to less precise diff results.
- gotcha Ensure that `react` and `react-dom` peer dependencies are installed and compatible with the specified version ranges (`^16.8 || ^17 || ^18`). Mismatched or missing peer dependencies can lead to runtime errors, rendering issues, or unexpected behavior related to React's lifecycle and hooks.
- gotcha The `show` prop controls the visibility of *unchanged* values in the JSON structure. Setting `show={false}` will hide parts of the JSON that are identical between the `left` and `right` objects, providing a concise 'diff-only' view. This behavior can be misunderstood if the expectation is to see the full structure with changes merely highlighted.
Install
-
npm install jsondiffpatch-react -
yarn add jsondiffpatch-react -
pnpm add jsondiffpatch-react
Imports
- JsonDiffReact
const JsonDiffReact = require('jsondiffpatch-react');import JsonDiffReact from 'jsondiffpatch-react';
Quickstart
import React, { useState } from 'react';
import JsonDiffReact from 'jsondiffpatch-react';
const App = () => {
const [leftData] = useState({
id: 1,
name: 'Alice',
age: 30,
hobbies: ['reading', 'coding', { type: 'music', genre: 'classical' }],
});
const [rightData] = useState({
id: 1,
name: 'Alice',
age: 31,
hobbies: ['reading', 'gaming', { type: 'music', genre: 'jazz' }],
status: 'active'
});
const [identicalData] = useState({ id: 2, name: 'Bob', email: 'bob@example.com' });
return (
<div style={{ padding: '20px' }}>
<h1>JSON Diff React Examples</h1>
<h2>Changed Data with Annotations</h2>
<p>Differences between two complex objects, showing annotations.</p>
<JsonDiffReact
left={leftData}
right={rightData}
show={true}
annotated={true}
tips="No differences detected."
objectHash={(obj) => obj.id || obj.name || JSON.stringify(obj)}
/>
<h2>Identical Data (with custom tips)</h2>
<p>When data is identical, a custom tip message is displayed.</p>
<JsonDiffReact
left={identicalData}
right={identicalData}
show={true}
annotated={false}
tips="The objects are exactly the same!"
/>
<h2>Hiding Unchanged Values</h2>
<p>Only the differing parts are displayed, providing a more concise view.</p>
<JsonDiffReact
left={{ a: 1, b: 2, c: { d: 4 } }}
right={{ a: 1, b: 3, c: { d: 4, e: 5 } }}
show={false}
annotated={false}
/>
</div>
);
};
export default App;