Created
May 23, 2017 09:00
-
-
Save lindskogen/5682585cc5f1a0becdad9956b3eb0ccb to your computer and use it in GitHub Desktop.
Convert DraftJS ContentState to html (only plaintext and mentions)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// @flow | |
import { RawDraftContentState } from 'draft-js' | |
type Mention = { | |
link: string, | |
name: string, | |
fullName: ?string, | |
id: number, | |
avatar: string | |
} | |
export const createUserLinkFromMention = (mention: Mention):string => { | |
return `<a href="${mention.link}" data-userid="${mention.id}">@${mention.name}</a>` | |
} | |
export default (rawContentState: RawDraftContentState):string => { | |
const { blocks, entityMap } = rawContentState | |
return blocks.map(block => { | |
const ranges = block.entityRanges.concat() | |
.sort((r1, r2) => r2.offset - r1.offset) | |
return ranges.reduce((string, range) => { | |
const mentionLink = createUserLinkFromMention(entityMap[range.key].data.mention) | |
return string.substring(0, range.offset) + mentionLink + string.substring(range.offset + range.length) | |
}, block.text) | |
}).join('') | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment