Build a Simple React Emoji Picker Component: A Beginner’s Guide

In today’s digital world, emojis have become an integral part of our communication. They add personality, express emotions, and make interactions more engaging. As web developers, we often encounter situations where we need to allow users to select emojis. Whether it’s for a chat application, a comment section, or a social media platform, an emoji picker is a valuable feature. This tutorial will guide you through building a simple yet functional React Emoji Picker component. We’ll break down the process step-by-step, making it easy for beginners to understand and implement.

Why Build an Emoji Picker?

Integrating an emoji picker into your application offers several benefits:

  • Enhanced User Experience: Emojis make communication more expressive and enjoyable.
  • Increased Engagement: Users are more likely to interact with features that offer a rich and engaging experience.
  • Modern Feel: Emojis are a modern communication tool, and incorporating them can make your application feel up-to-date.
  • Versatility: Emoji pickers can be used in various applications, from simple text fields to complex social platforms.

By building your own emoji picker, you gain control over its functionality, customization, and integration with your existing React application. This tutorial will provide you with the necessary knowledge and skills to create a component that meets your specific needs.

Prerequisites

Before we begin, ensure you have the following:

  • Node.js and npm (or yarn) installed: These are essential for managing project dependencies and running the development server.
  • Basic understanding of React: You should be familiar with components, JSX, state, and props.
  • Code editor: Such as VS Code, Sublime Text, or Atom.

Step-by-Step Guide to Building the React Emoji Picker

Let’s dive into the process of building your React Emoji Picker component. We’ll break it down into manageable steps, covering everything from setting up the project to handling user interactions.

1. Setting Up the React Project

First, create a new React project using Create React App. Open your terminal and run the following command:

npx create-react-app react-emoji-picker
cd react-emoji-picker

This will create a new React project named “react-emoji-picker”. Navigate into the project directory.

2. Installing Dependencies

For this project, we’ll use an emoji library to simplify the process of displaying emojis. We’ll use the ’emoji-mart’ library. Install it by running the following command:

npm install emoji-mart --save

This command installs the emoji-mart library and saves it as a dependency in your project’s package.json file.

3. Creating the Emoji Picker Component

Create a new file called EmojiPicker.js inside the src directory. This file will contain the code for our emoji picker component.

Here’s the basic structure of the component:

import React, { useState } from 'react';
import { Picker } from 'emoji-mart';
import 'emoji-mart/css/emoji-mart.css';

function EmojiPicker(props) {
  const [isOpen, setIsOpen] = useState(false);

  const handleEmojiSelect = (emoji) => {
    props.onEmojiSelect(emoji.native);
    setIsOpen(false);
  };

  return (
    <div>
      <button onClick={() => setIsOpen(!isOpen)}>😀</button>
      {isOpen && (
        <Picker
          set="apple"
          onSelect={handleEmojiSelect}
          title="Pick your emoji…"
          emoji="point_up"
        />
      )}
    </div>
  );
}

export default EmojiPicker;

Let’s break down this code:

  • Import Statements: We import React, useState, and the Picker component from ’emoji-mart’, along with the necessary CSS.
  • useState Hook: We use the useState hook to manage the state of the emoji picker (whether it’s open or closed).
  • handleEmojiSelect Function: This function is called when an emoji is selected. It calls the onEmojiSelect prop (which we’ll define later), passing the selected emoji’s native character. It then closes the picker.
  • JSX Structure:
    • A button that, when clicked, toggles the visibility of the emoji picker.
    • Conditionally renders the Picker component from ’emoji-mart’ if the picker is open.

4. Using the EmojiPicker Component

Now, let’s use the EmojiPicker component in our App.js file. Replace the contents of src/App.js with the following:

import React, { useState } from 'react';
import EmojiPicker from './EmojiPicker';

function App() {
  const [text, setText] = useState('');

  const handleEmojiSelect = (emoji) => {
    setText(text + emoji);
  };

  return (
    <div className="App">
      <h2>React Emoji Picker</h2>
      <input
        type="text"
        value={text}
        placeholder="Type something..."
        readOnly
      />
      <EmojiPicker onEmojiSelect={handleEmojiSelect} />
    </div>
  );
}

export default App;

Here’s what this code does:

  • Import Statements: We import React, useState, and our EmojiPicker component.
  • useState Hook: We use the useState hook to manage the text in an input field.
  • handleEmojiSelect Function: This function is passed to the EmojiPicker component as a prop. It receives the selected emoji and updates the text state by appending the emoji to the current text.
  • JSX Structure:
    • An input field to display the selected emojis.
    • The EmojiPicker component, which receives the handleEmojiSelect function as a prop.

5. Running the Application

Save both EmojiPicker.js and App.js. Then, in your terminal, run the following command to start the development server:

npm start

This will open your application in your browser (usually at http://localhost:3000). You should see an input field and an emoji button. Clicking the button will open the emoji picker. Selecting an emoji will add it to the input field.

Customization and Advanced Features

The basic emoji picker is functional, but you can enhance it with more features and customization options.

Customizing the Emoji Picker

The ’emoji-mart’ library provides several options for customizing the appearance and behavior of the picker:

  • Skin Tone: You can allow users to select their preferred skin tone for emojis.
  • Categories: You can customize which emoji categories are displayed (e.g., smileys & people, animals & nature, food & drink).
  • Theme: You can change the theme of the picker to match your application’s design (e.g., light or dark theme).
  • Search: The library includes a search feature that allows users to quickly find emojis.

Here’s an example of how to customize the Picker component:

<Picker
  set="apple"
  onSelect={handleEmojiSelect}
  title="Pick your emoji…"
  emoji="point_up"
  i18n={{ search: 'Search', categories: { people: 'People' } }}
  skin={SKIN_TONE_NEUTRAL}
/>

In this example:

  • set="apple" specifies the emoji set (e.g., Apple, Google, Twitter).
  • i18n allows you to customize the labels and text within the picker.
  • skin={SKIN_TONE_NEUTRAL} sets the default skin tone.

Adding More Features

You can also add other features to your emoji picker:

  • Recent Emojis: Store the emojis the user has recently selected and display them for quick access.
  • Custom Emojis: Allow users to add their custom emojis.
  • Keyboard Navigation: Implement keyboard navigation for easier emoji selection.

Common Mistakes and How to Fix Them

Here are some common mistakes beginners make when building an emoji picker and how to avoid them:

  • Incorrect Import Paths: Ensure that you import the ’emoji-mart’ components and CSS correctly. Double-check your import paths.
  • Prop Drilling: If you need to pass the selected emoji to multiple components, avoid prop drilling (passing the prop through several layers of components). Consider using React Context or a state management library like Redux or Zustand.
  • State Management: Make sure you manage the state of the emoji picker (open/closed) correctly. Use the useState hook to control the visibility of the picker.
  • CSS Conflicts: If you are experiencing styling issues, ensure there are no CSS conflicts between your styles and the ’emoji-mart’ styles. You might need to adjust your CSS to override the library’s styles.

Key Takeaways

Building a React Emoji Picker is a great way to learn about component creation, state management, and integrating third-party libraries. Here’s what you’ve learned:

  • Component Creation: You’ve created a reusable React component.
  • State Management: You’ve used the useState hook to manage the state of the emoji picker.
  • Third-Party Libraries: You’ve integrated the ’emoji-mart’ library to display emojis.
  • Props: You’ve passed props to the EmojiPicker component to handle emoji selection.
  • Customization: You’ve learned about customizing the emoji picker’s appearance and behavior.

FAQ

Here are some frequently asked questions about building a React Emoji Picker:

  1. How do I change the emoji set?

    You can specify the emoji set using the set prop in the Picker component (e.g., set="apple", set="google", set="twitter").

  2. How can I add custom emojis?

    You would need to modify the ’emoji-mart’ library or use a different library that supports custom emojis. You would need to provide a custom data source for your emojis.

  3. How do I handle multiple emoji pickers in my application?

    You can create multiple instances of the EmojiPicker component and pass different onEmojiSelect functions to each one, or use a context to share the selected emoji between the pickers.

  4. How can I improve the performance of my emoji picker?

    Consider lazy-loading the emoji picker or using a virtualized list if you have a very large number of emojis. Also, optimize the component’s rendering by using React.memo or other performance optimization techniques.

By following this tutorial, you’ve created a functional React Emoji Picker. Remember that this is just a starting point. You can customize and extend this component to meet your specific needs. Experiment with different features, explore the documentation of the ’emoji-mart’ library, and practice building more complex components. The more you practice, the more confident you’ll become in your React development skills.