To make rendering code diffs easier in a React app, we can use the React Diff Viewer library.
In this article, we’ll look at how to render code diffs with 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 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')
}
`;
const newStyles = {
variables: {
dark: {
highlightBackground: "#fefed5",
highlightGutterBackground: "#ffcd3c"
}
},
line: {
padding: "10px 2px",
"&:hover": {
background: "purple"
}
}
};
export default function App() {
return (
<div className="App">
<ReactDiffViewer
oldValue={oldCode}
newValue={newCode}
splitView={true}
styles={newStyles}
/>
</div>
);
}
We set it to an object with specific properties to set the styles.
highlightBackground sets the background color for highlights.
highlightGutterBackground sets the color for the gutter.
line is the styles for each line.
We can change the hover style of a line with the &:hover property.
Conclusion
We can use the React Diff Viewer component to add a code diff view into our React app.