Add widgets to changes
masterWidgets are React elements bound to specific changes, useful for features like code commenting or inline warnings.
How they work
- You provide a
widgetsobject to theDiffcomponent where keys are change keys (computed viagetChangeKey) and values are React elements. - In split view: A widget renders on the corresponding side if the change is an
additionordeletion. For other change types, it renders across the entire row. - Limitation: Each change can only render one widget. If multiple entries exist for the same change, only the first is rendered.
import {parseDiff, getChangeKey, Diff} from 'react-diff-view';
const getWidgets = hunks => {
const changes = hunks.reduce((result, {changes}) => [...result, ...changes], []);
const longLines = changes.filter(({content}) => content.length > 120);
return longLines.reduce(
(widgets, change) => {
const changeKey = getChangeKey(change);
return {
...widgets,
[changeKey]: <span className="error">Line too long</span>,
};
},
{}
);
};
const App = ({diffText}) => {
const files = parseDiff(diffText);
return (
<div>
{files.map(({hunks}, i) => (
<Diff
key={i}
hunks={hunks}
widgets={getWidgets(hunks)}
viewType="split"
/>
))}
</div>
);
};