0

I am using Draft.js and need to recurse into props.children to find components of type DraftEditorBlock.

For some reason, this doesn't really seem to work:

import React from 'react';
import { DraftEditorBlock } from 'draft-js';
...
export default class MyBlockRenderer extends React.Component {
  ...
  render() {
    const { children } = this.props;
    const firstChild = React.Children.toArray(children)[0];
    if (firstChild instanceof DraftEditorBlock) {
      ...
    }
    ...
  }
}

The line where instanceof is used causes this error:

TypeError: Right-hand side of 'instanceof' is not an object

What am I doing wrong?

mzedeler
  • 4,177
  • 4
  • 28
  • 41
  • 3
    Isn't the export called [`EditorBlock` instead of `DraftEditorBlock`](https://github.com/facebook/draft-js/blob/d24b80217beb76d4fa37e45835415a5ca7cb5a6f/src/Draft.js#L46)? – Tholle Aug 06 '18 at 14:03
  • It's possible that DraftEditorBlock is a stateless, functional component, rather than an object. – Joel Worsham Aug 06 '18 at 14:04
  • 2
    @JoelWorsham - Functions are still objects, so that wouldn't lead to the posted error message (it just wouldn't work). – T.J. Crowder Aug 06 '18 at 14:06
  • @T.J.Crowder + @Tholle: first bug is that I should use `EditorBlock` and not `DraftEditorBlock`, but now I just get `false` from all `instanceof` calls. Isn't there any sure fire way to tell if a component is of a certain class, even for functional components? – mzedeler Aug 13 '18 at 08:11

1 Answers1

1

read the render() methods in draftjs source top down. there are still many levels between DraftEditorBlock and DraftEditor.

I suggest you to cache all created/mounted DraftEditorBlocks other than find them in render() by:

  1. make a component inherit DraftEditorBlock, or new component with single <DraftEditorBlock ... /> child.
  2. map the text block type to your component with blockRendererFn.

should work.

Jiang YD
  • 3,205
  • 1
  • 14
  • 20