Search code examples
javascriptreactjsreact-reduxemoji

Add emojis to input


I am building a chat and I am using a library called emoji-picker-react and I want to add emojis to my text field and then send it as a message. I am using react so I will simplified the code for convinience. My messages are working but my emojis not so much. So far, if I click the emojis first and follow with some text, is fine. But if I type first and I try to add the emojis it won't work. Also, if I try to send emojis on its own, it won't work either. This is what I used to add emojis on my text field and both do the same.

This is where I try to add the emojis into my text field and is doing what I just explained:

const onEmojiClick = (e, emojiObject) => {
document.querySelector("#text").value += emojiObject.emoji
  // document.getElementById("text").value += emojiObject.emoji
};

And this is my input field:

<input
 id="text"
 style={inputStyles}
 type="text"
 placeholder="Type your message"
 value={message}
 onKeyPress={e => {
  if (e.key !== 'Enter') return;
    sendMessage(message);
  }
 }
 onChange={e => setMessageForm(e.target.value)}
/>

I am sure is something simple but can't get my head around it. I hope someone can guide on this.

Thank you!


Solution

  • Create a reference to the input node to get the cursor position and update the message value:

      const ref = useRef(null);
      const onEmojiClick = (event, emojiObject) => {
        const cursor = ref.current.selectionStart;
        const text = message.slice(0, cursor) + emojiObject.emoji + message.slice(cursor);
        setMessageForm(text);
      };
    

    jsx

    <input
      id="text"
      ref={ref}
      ...
    />
    

    https://stackblitz.com/edit/react-gg2akb?file=src%2FApp.js