DraftJS Tip — Getting the bounding rect of a content block in DraftJS

Is there a way to grab the bounding rect of a sentence in draft? Or do I need to setup some kind of decorator/custom block function to get that information?

This question has originally been asked on the official DraftJS slack group.


The blocks in DraftJS are converted to content editable divs. You might need the bounding client of a block for a variety of reasons — one instance: getting the positional information to place a widget along side the block appropriately.

The top level node of all content blocks in a DraftJS editor instance are divs with data-offset-key attributes, with values of the form ijkl-0-0 where ijkl is equal to the key prop of the content block.

Using the above information, and the following snippet of code, one can easily get the bounding rect information of a content block:

document.querySelector(
    `div[data-offset-key="${blockKey}-0-0"]`
).getBoundingClientRect();

blockKey is the key of the corresponding content block.

Write your comment…

This helped big time! Thanks again Sai!

I'm glad it was of help! :)

Reply to this…