React js diff2html Cannot read property 'getJsonFromDiff' of undefined

1.1k Views Asked by At

Link: codesandbox

I'm having the following problem can anyone help me out?

Error:

Cannot read property 'getJsonFromDiff' of undefined

-> let outStr = Diff2Html.getJsonFromDiff(dd, {

CodeDiff.js:

import React, { Component } from "react";
import PropTypes from "prop-types";
import { createPatch } from "diff";
import { Diff2Html } from "diff2html";
import { InlineMath } from "react-katex/dist/react-katex";
import "highlight.js/styles/googlecode.css";
import "diff2html/lib/diff2html";

function CodeDiff(props) {
  const { oldStr, newStr, context, outputFormat } = props;
  const createdHtml = (oldString, newString, context, outputFormat) => {
    function hljs(html) {
      return html.replace(
        /<span class="d2h-code-line-ctn">(.+?)<\/span>/g,
        '<span class="d2h-code-line-ctn"><code>$1</code></span>'
      );
    }
    let args = [
      "",
      oldString || "",
      newString || "",
      "",
      "",
      { context: context }
    ];
    let dd = createPatch(...args);
    let outStr = Diff2Html.getJsonFromDiff(dd, {
      inputFormat: "diff",
      outputFormat: outputFormat,
      showFiles: false,
      matching: "lines"
    });
    let html = Diff2Html.getPrettyHtml(outStr, {
      inputFormat: "json",
      outputFormat: outputFormat,
      showFiles: false,
      matching: "lines"
    });
    return hljs(html);
  };
  const html = () => createdHtml(oldStr, newStr, context, outputFormat);
  return (
    <div id="code-diff" dangerouslySetInnerHTML={{ __html: html() }}></div>
  );
}
CodeDiff.propTypes = {
  oldStr: PropTypes.string.isRequired,
  newStr: PropTypes.string.isRequired,
  context: PropTypes.number,
  outputFormat: PropTypes.string
};
CodeDiff.defaultProps = {
  oldStr: "",
  newStr: "",
  context: 5,
  outputFormat: "line-by-line"
};

export default CodeDiff;

2

There are 2 best solutions below

0
On

I had the same question, I was able to get access to these functions like this:

import * as Diff2HtmlLib from 'diff2html';

Diff2HtmlLib.Diff2Html.getJsonFromDiff(diff, diffOptions)
0
On

Well, "diff2html" library exposes only "html" and "parse" functions, so in order to use it from single object Diff2Html like you want you have to import it diffrently, like so:

import * as Diff2Html from "diff2html";

But then there are no such things there as getJsonFromDiff and getPrettyHtml Not sure where you got those from, getJsonFromDiff is actually a test name in their github - https://github.com/rtfpessoa/diff2html/search?q=getJsonFromDiff But it is not a function. And there is not at all such thing as getPrettyHtml

So i suppose you wanted to use parse (instead of getJsonFromDiff) and html (instead of getPrettyHtml) that way it works fine as far as i can tell - https://codesandbox.io/s/material-demo-forked-jhljq?file=/CodeDiff.js:114-153