draft-js icon indicating copy to clipboard operation
draft-js copied to clipboard

How to set block data?

Open goddyZhao opened this issue 10 years ago • 8 comments

I want to insert a code block and specify the language of the code block like JavaScript for code highlight (I use decorator to make it), but since I use RichUtils.toggleBlockType, how can I add block data on that? Thanks!

goddyZhao avatar Sep 26 '16 01:09 goddyZhao

make a selection by SelectionState.createempty then Modifier.setBlockData

jan4984 avatar Sep 26 '16 02:09 jan4984

thanks @jan4984 !

goddyZhao avatar Sep 26 '16 02:09 goddyZhao

Any concrete example on how to do this?

agungsb avatar Jun 16 '19 23:06 agungsb

@goddyZhao & @jan4984 could you show us an example of how to use Modifier.setBlockData() ? What is the Map<any,any> and how do we set it?

promerorgz avatar Jun 21 '19 22:06 promerorgz

And can anyone explain why those arguments are used? For instance, why do we need SelectionState in Modifier.setBlockData? What will happen if selection state is greater than the block we want to "tag"? If Modifier is adding block metadata, shouldn't then we pass the ContentBlock instead? And as @promerorgz asked, what is Map<any, any>? What should we pass there, why do we need a Map?

negyxo avatar Jul 27 '19 08:07 negyxo

@negyxo that is true, you can modify contentblock directly by using immutable-js API, but you will need lots of codes(about 10 lines I think), Modifier is a just helper class

jan4984 avatar Jul 31 '19 16:07 jan4984

Any concrete example on how to do this?

here's a good reference of how to use setDataBlock

https://sendgrid.com/blog/how-we-use-draft-js-at-sendgrid/

NishantDesai1306 avatar Jul 21 '20 13:07 NishantDesai1306

Any concrete example on how to do this?

It's been a while but maybe its useful to someone

I was trying to set data on a block as soon as the user leave it.

const setBlockLock = (editorState, block, isLocked) => {
  // save the actual selection to use later
  const userSelection = editorState.getSelection()

  const newData = isLocked ? block.data.set("locked", isLocked) : block.data.delete("locked")    

  // create a new selection with the block I want to change
  const selection = SelectionState.createEmpty(block.key)

  const newContent = Modifier.setBlockData(editorState.getCurrentContent(), selection, newData)

  const newEditor = EditorState.push(editorState, newContent, 'change-block-data')

  // return a new editor state, applying the selection we stored before
  return EditorState.forceSelection(newEditor, userSelection)
}

mcbattirola avatar Jun 23 '21 11:06 mcbattirola