0

I'm creating a ContentState from an Array of blocks that were created programmatically, but when I created an EditorState using the ContentState nothing shows up in the edtior, is this the right way to create custom blocks?

const dummyBlocks = [ new ContentBlock({
  key: genKey(),
  type: 'atomic',
  depth: 0,
  text: "This is a test block 1",
  characterList: List()

}), new ContentBlock({
  key: genKey(),
  type: 'atomic',
  depth: 0,
  text: "This is a test block 2",
  characterList: List()

})];

const cs = ContentState.createFromBlockArray(dummyBlocks);

const es = EditorState.createWithContent(cs);
ryudice
  • 36,476
  • 32
  • 115
  • 163

1 Answers1

1

When you're creating blocks manually, you need to pass a List to characterList that's the correct length for the text of the block you are creating.

So, instead of characterList: List() what you need will look more like this:

const charData = CharacterMetadata.create();
const firstText = "This is a test block 1";
const secondText = "This is a test block 2";
const dummyBlocks = [ new ContentBlock({
  key: genKey(),
  type: 'atomic',
  depth: 0,
  text: firstText,
  characterList: List(Repeat(charData, firstText.length))

}), new ContentBlock({
  key: genKey(),
  type: 'atomic',
  depth: 0,
  text: secondText,
  characterList: List(Repeat(charData, secondText.length))

})];

You can read more about CharacterMetadata here: https://draftjs.org/docs/api-reference-character-metadata.html#content

This was directly inspired by draft's AtomicBlockUtils, which you can find here: https://github.com/facebook/draft-js/blob/514490b1322e1c123524eae97d4aea25b4da16ce/src/model/modifier/AtomicBlockUtils.js#L66

kaylee42
  • 11
  • 3