Skip to content

Instantly share code, notes, and snippets.

@lindskogen
Created May 23, 2017 09:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lindskogen/5682585cc5f1a0becdad9956b3eb0ccb to your computer and use it in GitHub Desktop.
Save lindskogen/5682585cc5f1a0becdad9956b3eb0ccb to your computer and use it in GitHub Desktop.
Convert DraftJS ContentState to html (only plaintext and mentions)
// @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