This is the third in an ongoing series of posts.
- draft-js pieces
- draft-js EditorState
- draft-js ContentState
- draft-js ContentBlock
- draft-js SelectionState
- draft-js highlight text
- draft-js styling a ContentBlock
This is the third 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 ContentState.
The last post was about EditorState, The EditorState essentially maintains a stack of ContentState objects. Each representing a subsequent change in state. As I mentioned in that post it also has some convenience functions for accessing the current ContentState including
const myCurrentContent = myEditorState.getCurrentContent()
What data ContentState holds is not that extensive, it has a block map ( a collection of ContentBlocks ) a beforeSelection and an afterSelection both returning a SelectionState object. But it does have a lot of functions that allow you to access the pieces of the document, namely the ContentBlocks.
So for instance, you can
const targetBlock = myCurrentContent.getBlockForKey(myTargetKey);
which returns a specific ContentBlock, you can then interrogate it or use it as a target to modify. That’s odd wording but basically everything is immutable, so most of the top level draft-js objects don’t provide set methods. You generally take a piece you want to modify and do so via the immutable.js api or via functions provided by draft-js. These pieces are generally either a selection or whole ContentBlock. We will very soon be getting into those actions as that’s really the fun stuff, but you must understand the pieces before the modifying helper functions really make sense.
So the ContentState is a snapshot of the state of your document with methods to help you find what you are looking for in the document. The most basic of which is getBlockForKey(key). It seems that they provide a very nice feature of letting you compare the previous snapshot to the current snapshot via getBefore() and getAfter() methods. e.g.
In any case this is the bulk of the api on ContentState. I’m not going to go over every function as the docs do a nice job of that. I’m just going to say that if you need a specific block or selection, and/or you want to compare what it was to what it is, then you want to come to the ContentState.