Categories
React

Add a Diff Display into a React App with the jsdiff Library

Spread the love

Sometimes, we may want to show the difference between 2 pieces of text to the user.

We can do this easily with the jsdiff library.

In this article, we’ll look at how we can use the jsdiff library with React.

Installation

We can install the library by running:

npm install diff --save

Add the Diff Display

We can add the diff display into our React app by writing the following:

import React from "react";
const Diff = require("diff");

const one = "beep boop";
const other = "beep boob blah";

const diff = Diff.diffChars(one, other);
export default function App() {
  return (
    <div className="App">
      {diff.map((part) => {
        const color = part.added ? "green" : part.removed ? "red" : "grey";
        return <span style={{ color }}>{part.value}</span>;
      })}
    </div>
  );
}

The one and other strings are what we want to diff.

We call Diff.diffChars with both of them to create the diff array.

Then we call diff.map to map the diffed parts to span elements.

part.added is true when the part is in the 2nd string but not the first.

part.removed is true when the part isn’t in the 2nd string but it’s in the first.

part.value has the value of the part.

Now we should see the comparisons displayed.

The display will show the 2nd string which is the other string, with the parts that are added to the first string in green and the parts that are removed from the first string in red.

We can show diffed JSON objects ith the diffJson method.

To use it, we write:

import React from "react";
const Diff = require("diff");

const one = { foo: "bar", bar: "baz" };
const other = { foo: "bar", bar: "bar" };

const diff = Diff.diffJson(one, other);
export default function App() {
  return (
    <div className="App">
      {diff.map((part) => {
        const color = part.added ? "green" : part.removed ? "red" : "grey";
        return <span style={{ color }}>{part.value}</span>;
      })}
    </div>
  );
}

It’ll show the properties that are added, removed, or stay the same with the same colors that we set.

Other methods include the diffTrimmedLines method to compare text line by line ignoring leading and trailing whitespace.

diffSentences compares 2 blocks of text sentence by sentence.

diffCss compares 2 CSS tokens.

diffArrays compare the entries of 2 arrays with the === operator.

They all return an array of objects with the same properties as in the examples.

Conclusion

We can use the jsdiff library with React to show text diffs to users easily.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *