Skip to content

Instantly share code, notes, and snippets.

@thomasboyt
Last active March 14, 2019 12:24
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save thomasboyt/b5ef9ed8606ce6d93982 to your computer and use it in GitHub Desktop.
Save thomasboyt/b5ef9ed8606ce6d93982 to your computer and use it in GitHub Desktop.
/** @jsx React.DOM */
define([
'react',
'modernizr',
'punycode'
], function(React, Modernizr, punycode) {
/**
* Replaces the emojis in a text string with <img> tags
*/
var isEmojiCode = function(charCode) {
return (
( charCode >= 0x1F300 && charCode <= 0x1F5FF ) ||
( charCode >= 0x1F600 && charCode <= 0x1F64F ) ||
( charCode >= 0x1F680 && charCode <= 0x1F6FF ) ||
( charCode >= 0x2600 && charCode <= 0x26FF )
);
};
var emojiTransform = function(text) {
var decoded = punycode.ucs2.decode(text);
var entries = [];
decoded.forEach(function(charCode, idx) {
if ( isEmojiCode(charCode) ) {
// emoji char encountered, insert img tag
var hexCode = charCode.toString(16);
entries.push(
<img src={"/w/images/emoji/" + hexCode + ".png"} key={idx} />
);
} else {
var char = punycode.ucs2.encode([charCode]);
var lastIdx = entries.length - 1;
if ( typeof entries[lastIdx] === 'string' ) {
entries[lastIdx] += char;
} else {
entries.push(char);
}
}
});
return entries;
};
var Emojify = React.createClass({
propTypes: {
text: React.PropTypes.string.isRequired
},
shouldComponentUpdate: function(nextProps) {
return nextProps.text !== this.props.text;
},
render: function() {
var emojifiedText = !Modernizr.emoji ? emojiTransform(this.props.text) : this.props.text;
return (
<span>{emojifiedText}</span>
);
}
});
return Emojify;
});
@Lendar
Copy link

Lendar commented Nov 22, 2014

Thanks, it was helpful.

For the reference, here is code for GitHub's hosted set of emoji:

<img src={"https://assets-cdn.github.com/images/icons/emoji/unicode/" + hexCode + ".png"} key={idx} />

Example https://assets-cdn.github.com/images/icons/emoji/unicode/1f42f.png

@jblz
Copy link

jblz commented Feb 4, 2015

Thanks for this!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment