How to add an emoji picker to an input field in react app

How to add an emoji picker to an input field in react app

Creating a new react app

npx create-react-app

Starting the app -

# npm
npm start
# yarn
yarn start

Installing the required dependencies -

# npm
npm install emoji-mart
# yarn
yarn add emoji-mart

Cleanup process

  • Delete everything inside the div in App.js and remove the import of logo.svg on top.
  • Delete logo.svg file.
  • Delete everything in App.css.
  • In index.css add this line of code -
    * {
    margin: 0;
    }
    

Creating an input

import "./App.css";

function App() {
  return (
    <div className="app">
      <input type="text" placeholder="emoji picker demo" />
    </div>
  );
}

export default App;

Mapping to a state

import { useState } from "react";
import "./App.css";

function App() {
  const [input, setInput] = useState("");

  return (
    <div className="app">
      <input
        value={input}
        onChange={(e) => setInput(e.target.value)}
        type="text"
        placeholder="emoji picker demo"
      />
    </div>
  );
}

export default App;

Creating an svg button for emojis

     <button>
        <svg
          xmlns="http://www.w3.org/2000/svg"
          className="icon"
          fill="none"
          viewBox="0 0 24 24"
          stroke="currentColor"
        >
          <path
            stroke-linecap="round"
            stroke-linejoin="round"
            stroke-width="2"
            d="M14.828 14.828a4 4 0 01-5.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
          />
        </svg>
      </button>

Adding some styles in App.css

.icon {
  height: 40px;
  width: 40px;
}

.button {
  background: transparent;
  outline: none;
  border: none;
}

Creating a state for showing picker

const [showEmojis, setShowEmojis] = useState(false);

Attaching it to the onClick of button

<button className="button" onClick={() => setShowEmojis(!showEmojis)}>

Rendering the emoji picker

 {showEmojis && (
        <div>
          <Picker />
        </div>
      )}

We will import Picker and the CSS like this

import { Picker } from "emoji-mart";
import "emoji-mart/css/emoji-mart.css";

Adding the emojis with the text in the input

Add an onSelect to the picker

<Picker onSelect={addEmoji} />

Create the addEmoji function

  const addEmoji = (e) => {
    let sym = e.unified.split("-");
    let codesArray = [];
    sym.forEach((el) => codesArray.push("0x" + el));
    let emoji = String.fromCodePoint(...codesArray);
    setInput(input + emoji);
  };

Now our emoji picker is working! 🥳

image.png

Useful links -

Github repository

ReactJS docs

All socials

Did you find this article valuable?

Support Avneesh Agarwal by becoming a sponsor. Any amount is appreciated!