pavittarx / editorjs-html

A javascript library to parse editorjs clean data to html. It is adaptable and usable in all kind of projects.
https://runkit.com/pavittarx/editorjs-html-example
MIT License
328 stars 61 forks source link

FIXED - Handle Table? #51

Closed mihaiicey closed 1 year ago

mihaiicey commented 1 year ago

Could you make it compatible with editorjs-table - https://github.com/codinova-tech/editorjs-table ? Currently if I want to render the table, it crashes when rendering because the json differs :(

Normal code (list):

{
  "type": "list",
  "style": "unordered",
  "data": {
    "items": [
      "HJM",
      "HJM"
    ]
  }
}

Table code:

{
  "type": "table",
  "data": {
    "content": [
      ["s", "s"] - it crases here :( - Error: Objects are not valid as a React child (found: [object Error]). If you meant to render a collection of children, use an array instead.
    ]
  }
}
mihaiicey commented 1 year ago

I'm sorry, I didn't understand exactly how to do it from the documentation. Here is my code, maybe someone else has problems.

//components/EditorJsRenderer.tsx

import { OutputData } from '@editorjs/editorjs';
import React from 'react';
import edjsHTML from 'editorjs-html';

type Props = {
  data: OutputData;
};
type ParsedContent = string | JSX.Element;

const customParser = (block: any) => {
  const rowData = block.data.content;
  return `
      <table class="text-center mx-auto">
        <tbody>
          ${rowData
            .map(
              (row: any) => `
            <tr>
              ${row
                .map(
                  (cell: string) => `
                <td>${cell}</td>
              `
                )
                .join('')}
            </tr>
          `
            )
            .join('')}
        </tbody>
      </table>
      `;
};

const EditorJsRenderer = ({ data }: Props) => {
  const EditorJsToHtml = edjsHTML({
    table: customParser
  });
  const html = EditorJsToHtml.parse(data);
  return (
    <div className='prose ContractTemplate max-w-full' key={data.time}>
      {html.map((item: any, index) => {
        if (typeof item === 'string') {
          return <div key={index} dangerouslySetInnerHTML={{ __html: item }}></div>;
        }
      })}
    </div>
  );
};

export default EditorJsRenderer;