Created
January 2, 2018 09:39
-
-
Save veob/1dfe6cfb39a4a5768ec66c5e2cec9574 to your computer and use it in GitHub Desktop.
Render native emoji as emoji-mart components (quick solution)
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
const _ = require('lodash'); | |
const React = require('react'); | |
const propTypes = require('prop-types'); | |
const {Emoji, emojiIndex} = require('emoji-mart'); | |
// https://stackoverflow.com/a/45138005/3061229 | |
const regexp = new RegExp( | |
'[\u{1f300}-\u{1f5ff}\u{1f900}-\u{1f9ff}\u{1f600}-\u{1f64f}' + | |
'\u{1f680}-\u{1f6ff}\u{2600}-\u{26ff}\u{2700}-\u{27bf}\u{1f1e6}' + | |
'-\u{1f1ff}\u{1f191}-\u{1f251}\u{1f004}\u{1f0cf}\u{1f170}-\u{1f171}' + | |
'\u{1f17e}-\u{1f17f}\u{1f18e}\u{3030}\u{2b50}\u{2b55}\u{2934}-\u{2935}' + | |
'\u{2b05}-\u{2b07}\u{2b1b}-\u{2b1c}\u{3297}\u{3299}\u{303d}' + | |
'\u{00a9}\u{00ae}\u{2122}\u{23f3}\u{24c2}\u{23e9}-\u{23ef}' + | |
'\u{25b6}\u{23f8}-\u{23fa}]', 'gu' | |
); | |
const getByNative = function(native) { | |
return _.find(emojiIndex.emojis, {native}); | |
}; | |
function EmojiText({children}) { | |
let matchArr; | |
let lastOffset = 0; | |
const parts = []; | |
while ((matchArr = regexp.exec(children)) !== null) { | |
parts.push(children.substring(lastOffset, matchArr.index)); | |
// skip 2 chars, because an emoji is 2-chars wide | |
lastOffset = matchArr.index + 2; | |
const emoji = getByNative(matchArr[0]); | |
if (emoji) { | |
parts.push(<Emoji emoji={emoji.id} size={16} />); | |
} else { | |
parts.push(matchArr[0]); | |
} | |
} | |
parts.push(children.substring(lastOffset, children.length)); | |
return ( | |
<span> | |
{parts.length ? | |
_.map(parts, (part, i) => <span key={i}>{part}</span>) : | |
children | |
} | |
</span> | |
); | |
} | |
EmojiText.propTypes = { | |
children: propTypes.string.isRequired | |
}; | |
module.exports = EmojiText; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example
Input:
Output: