How To Highlight JSON as Text In React

Viewed 611

I was given a task to highlight JSON coming from Api in React. enter image description here

I successully showed JSON as text. But problem was with hightlighing text. I found function for highlighting text in Vanilla JS. When I convert that code in React, it doesn't work properly. Can anybody check where I made a mistake.

App.js

import "./styles.css";

export default function App() {
  const data = new Array(1).fill({
    id: 1,
    isTrue: true,
    time: "15.02.2021 (13:33:11) - 10.01.2021 (10:20:55)",
    username: "ums_user_11",
    pinfl: 13212313212123,
    passSerial: "null",
    client_id: "UMS"
  });

  function syntaxHighlight(json) {
    json = json
      .replace(/&/g, "&")
      .replace(/</g, "&lt;")
      .replace(/>/g, "&gt;");
    return json.replace(
      /("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g,
      function (match) {
        var cls = "number";
        if (/^"/.test(match)) {
          if (/:$/.test(match)) {
            cls = "key";
          } else {
            cls = "string";
          }
        } else if (/true|false/.test(match)) {
          cls = "boolean";
        } else if (/null/.test(match)) {
          cls = "null";
        }
        return `<span class={"${cls}"}>${match}</span>`;
      }
    );
  }

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <pre>{syntaxHighlight(JSON.stringify(data[0], null, 2))}</pre>
    </div>
  );
}

style.css

pre {
  outline: 1px solid #ccc;
  padding: 5px;
  margin: 5px;
}
.string {
  color: green;
}
.number {
  color: darkorange;
}
.boolean {
  color: blue;
}
.null {
  color: magenta;
}
.key {
  color: red;
}

Full code in case: https://codesandbox.io/s/mystifying-dew-je0zp?file=/src/App.js

0 Answers
Related