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.

18
Subscribe to my newsletter

Read articles from Sai Kishore Komanduri directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Sai Kishore Komanduri
Sai Kishore Komanduri

I have been in love with computers and everything related since I played my first game of Dangerous Dave back in the 90s. Graduating with a master's degree in Biology, and a bachelor's in Pharmacy; I have been fortunate enough to dabble my hands in things ranging from copywriting to computer networks. I love pixel art! I've written a few more things about me, here and here!