Render Code Diffs in a React App with the React Diff Viewer Library

John Au-Yeung
Level Up Coding
Published in
2 min readJan 12, 2021

--

Photo by Kevin Ku on Unsplash

To make rendering code diffs easier in a React app, we can use the React Diff Viewer library.

Installation

We can install the package by running:

npm i react-diff-viewer

or:

yarn add react-diff-viewer

Rendering the Diffs

To render the diffs in our React app, we can use the ReactDiffViewer component.

For example, we can write:

import React from "react";
import ReactDiffViewer from "react-diff-viewer";
const oldCode = `
const a = 10
const b = 10
const c = () => console.log('foo')

if(a > 10) {
console.log('bar')
}

console.log('done')
`;
const newCode = `
const a = 10
const boo = 10

if(a === 10) {
console.log('bar')
}
`;
export default function App() {
return (
<div className="App">
<ReactDiffViewer oldValue={oldCode} newValue={newCode} splitView={true} />
</div>
);
}

We pass in the old code string into the oldValue prop and the new code into the newValue prop.

Also, we can hide the line numbers with the hideLineNumers prop.

splitView shows the old and new code side by side.

Compare Method

We can change the compare method of for diffing with the compareMethod prop:

import React from "react";
import ReactDiffViewer from "react-diff-viewer";
import Prism from "prismjs";
const oldCode = `
const a = 10
const b = 10
const c = () => console.log('foo')

if(a > 10) {
console.log('bar')
}

console.log('done')
`;
const newCode = `
const a = 10
const boo = 10

if(a === 10) {
console.log('bar')
}
`;
export default function App() {
return (
<div className="App">
<ReactDiffViewer
oldValue={oldCode}
newValue={newCode}
splitView={true}
compareMethod="diffWords"
/>
</div>
);
}

Styling

We can change the styles by passing in the styles prop:

import React from "react";
import…

--

--