Draft-js SelectionState

This is the first in an ongoing series of posts.

  1. draft-js pieces
  2. draft-js EditorState
  3. draft-js ContentState
  4. draft-js ContentBlock
  5. draft-js SelectionState
  6. draft-js highlight text
  7. draft-js styling a ContentBlock

This is the fifth in a series of posts about draft-js.  The first post was an overview of the pieces and subsequent posts have been a little deeper dive into said pieces.  This post will be about SelectionState.

SelectionState is essentially either the exact character spot where the cursor is blinking or a range of characters that have been highlighted.  You can get the SelectionState from various places as mentioned in previous posts i.e. EditorState, or ContentState.

In the DOM a selection is represented as an anchor and a focus point.  This representation ( and other aspects of the DOM selection ) are very helpful for rendering in the DOM, but not as necessary for the purposes of editing a document in code.  Thus draft-js has created a slightly different api.  It is comprised of key(s) and offset(s).  The key is the ContentBlock key where the point is positioned, and the offset value is the character offset in that block.  While the api also makes available the anchor and focus, you generally will be interacting with the key and offset via functions like these

const myStartKey = mySelection.getStartKey() // useful for finding the block that the selection starts in

const myStartOffset = mySelection.getStartOffset() // useful for finding the beginning of the selection.

corresponding End methods

This is really most of what’s in the SelectionState object.  Not much too it but it is super useful for decorating your document with different styles and functionality.  The workflow would be something like

I recognize that this is very dissatisfying as I’m just telling you about what pieces can change rather than how to actually change them and get the result you are after.  But now that this part is out of the way subsequent posts can deal with how to actually use these pieces to affect change.  Regrettably, but perhaps understandably, it’s not just as easy as grabbing an object and changing properties on it.  But there are lots of helper functions that allow you to do different things easily and we will be hit those next.

Advertisements
Draft-js SelectionState