javascriptreactjsdraftjs

How do you get the content length from raw DraftJS data?


I am storing the contents of my DraftJS editor in my database as a JSON string after running it through convertToRaw(editorState.getCurrentContent()).

An example of what is stored in the database:

{"blocks": [{"key": "1m9md", "data": {}, "text": "", "type": "unstyled", "depth": 0, "entityRanges": [], "inlineStyleRanges": []}, {"key": "c8gek", "data": {}, "text": "Lorem ipsum dolor sit amet, eu habitasse magna aliquam non et faucibus, aliquet et ante tempus vestibulum pellentesque, ligula curabitur. Eum torquent dapibus est, ac consectetuer integer. Luctus pellentesque ut pellentesque. Libero id lorem bibendum, sed elementum, adipiscing mollis, aenean pellentesque ligula nonummy pellentesque ornare urna, sit a sagittis wisi rhoncus tellus congue. Risus tristique blandit in nascetur, mauris quisque sed erat error integer accumsan, ante facilisi. Libero proin nunc vestibulum tempus, consectetuer aliquam sed velit morbi quis, molestie accumsan in, lacus eu, aliquam odio porta tellus ac. Praesent aliquet.", "type": "unstyled", "depth": 0, "entityRanges": [], "inlineStyleRanges": []}, {"key": "7mv98", "data": {}, "text": "", "type": "unstyled", "depth": 0, "entityRanges": [], "inlineStyleRanges": []}, {"key": "63ck4", "data": {}, "text": "", "type": "unstyled", "depth": 0, "entityRanges": [], "inlineStyleRanges": []}], "entityMap": {}}

Now, when displaying this to the user as HTML, I want to check if for each section they actually entered any text into the DraftJS editor. Even if they leave it empty, the database stores:

{"blocks": [{"key": "6n2bu", "data": {}, "text": "", "type": "unstyled", "depth": 0, "entityRanges": [], "inlineStyleRanges": []}], "entityMap": {}}

There seems to be no clear way to programmatically check the length of the content (or that it exists at all).

I am looking for a way to check for the existence of content before converting it to HTML and rendering it using React.


Solution

  • You can use ContentState.hasText()

    In order to see if it is empty.

    Otherwise, you can always call ContentState.getPlainText() in order to get the full text, and then you can get the length.

    e.g. myContent.getPlainText(' ').length