➡️ How to add an emoji picker to your React chat app.
I’m using emoji-mart library, this is how our thing is going to look:
STEP 1: run: npm i emoji-mart
to add the dependency.
STEP 2: import the emoji-mart in the component you want to use it in:
import 'emoji-mart/css/emoji-mart.css'import { Picker } from 'emoji-mart'
STEP 3: render the picker.
This is my text input form:
<form onSubmit={this.handleSubmit}>
<input
type="text"
value={this.state.text}
onChange={this.handleChange}
placeholder="Type a message here then hit ENTER"
/>
</form>
I placed my Emoji Picker outside the form in a span element and then gave it an absolute position with CSS.
<span>
<Picker onSelect={this.addEmoji} />
</span>
STEP 4: add emojis to messages.
Handle text input onChange:
handleChange = e => {
this.setState({ text: e.target.value })
}
If were to console.log(e)
, this is what we would get:
addEmoji solutions:
You can go for an easy one which is to use e.native:
addEmoji = e => {
let emoji = e.native;
this.setState({
text: this.state.text + emoji
});
};
If it doesn’t work for some characters, this is another approach:
addEmoji = e => {
let sym = e.unified.split('-')
let codesArray = []
sym.forEach(el => codesArray.push('0x' + el))
let emoji = String.fromCodePoint(...codesArray)
this.setState({
text: this.state.text + emoji
})
}
We can see that unified
is in Unicode (hex). We need to add ‘0x’
in the front of the code for it to become an emoji.
Most emojis have a hex code no longer than 5 characters. But there are emojis that have longer codes, such as this ‘man-woman-girl-boy’ emoji:
What we are doing here is taking a long code such as “1f468–200d-1f469–200d-1f467–200d-1f466”
, splitting it on (‘-’)
, adding ‘0x’
to each element and then pushing them into a new array.
String.fromCodePoint
is what will turn it into an emoji. So we take the content of the array with a spread operator …codesArray
and let the magic (or a female technologist) happen:
Then we handle submit:
handleSubmit = e => {
e.preventDefault()
postMessage(this.state) //send to backend
this.setState({ text: '' }) //reset input field to empty
}
You can see how I did it here in my NewMessageForm
component in chat-client
repo. You can also see how I implemented this toggle there.
Was this useful? Any questions? Let me know in the comments.
We built this chat app (MVP!) for our Mod4 project (while at //Flatiron School ❤️), feel free to check it out on GitHub:
front-end chat-client (React),
back-end chat-server (Rails API)