Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing table support in draft js

I’m working on a hack for table support (one level deep) using draft.js

I have one requirement: All existing editor functionality needs to also work inside this table

I present three choices to you, please pick one and explain why you did so:

  1. Nested Editors (One for each cell) - I’m guessing I’d have to implement selection handling between editors
  2. Table cells as enitites, wrapped in a Custom Block Component that renders the table and manages columns and rows. - It'll be costly to develop this, since I'll need to interfere with a lot of event handling and rendering.
  3. Is there another way that you think could work better?
like image 320
Julian Krispel-Samsel Avatar asked Oct 17 '22 11:10

Julian Krispel-Samsel


1 Answers

I have a solution for tables in draft-js that works pretty well for us. I do not use separate editors for each cell, just regular EditorBlocks that are all part of the main editor tree. There's a working example here https://draft-js-rte-evanmorrison.netlify.app/ and the repo here https://github.com/EvanMorrison/draft-js-rte

  1. I have a "TableCell" custom block type that primarily just renders a standard EditorBlock, but uses React.createPortal to render into the applicable table cell.

  2. The information necessary to recreate the table structure is stored in the metadata of the first cell of the table.

  3. When rendering the first block, I render its EditorBlock component wrapped in the full DOM structure of the table. The <th>/<td> tags for all but the first cell are empty, but are given a data attribute corresponding to their position in the table.

  4. Then I use ReactDOM.createPortal when rendering each of the subsequent TableCell blocks into the correct position in the table.

As far as draft-js is concerned it's just rendering blocks in the usual linear fashion. This makes editing, managing selection state, & the import/export of html no more difficult than for any other block type for the most part. Though you do have to take precautions with selections and editing that cross into or out of the table.

like image 105
EvanMorrison Avatar answered Nov 01 '22 16:11

EvanMorrison