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

Written by

in

In today’s digital world, emojis have become an integral part of our communication. They add personality, emotion, and clarity to our messages. Imagine building a simple React application that allows users to easily select and insert emojis into their text fields. This project is not only fun but also a fantastic way to solidify your understanding of React components, state management, and event handling. Whether you’re a beginner looking to learn the ropes or an intermediate developer seeking to reinforce your skills, this guide will walk you through the process step-by-step.

Why Build an Emoji Picker?

Creating an emoji picker is a practical and engaging project for several reasons:

  • Practical Application: Emoji pickers are useful in various applications, from chat interfaces to comment sections, enhancing user experience and engagement.
  • Core React Concepts: It allows you to practice essential React concepts, including component creation, state management, event handling, and rendering lists.
  • Fun and Engaging: Working with emojis is inherently enjoyable, making the learning process more motivating and less tedious.
  • Scalability: The skills you learn can be applied to more complex projects, such as building custom UI components or interactive web applications.

Project Setup and Prerequisites

Before we dive into the code, let’s ensure you have the necessary tools and environment set up:

  • Node.js and npm/yarn: You need Node.js and either npm (Node Package Manager) or yarn installed on your system. These are essential for managing project dependencies.
  • Code Editor: Choose your preferred code editor (e.g., VS Code, Sublime Text, Atom).
  • Basic Understanding of HTML, CSS, and JavaScript: Familiarity with these technologies is crucial for understanding the concepts and building the application.

Let’s start by creating a new React application using Create React App. Open your terminal and run the following command:

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

This will set up a new React project with all the necessary configurations. Now, let’s clean up the boilerplate code. Open the src directory and delete the following files: App.css, App.test.js, logo.svg, and setupTests.js. Then, modify App.js to remove the unnecessary imports and content, leaving only the basic structure:

import React from 'react';

function App() {
  return (
    <div className="App">
      <h1>Emoji Picker</h1>
    </div>
  );
}

export default App;

Finally, create a new file named EmojiList.js inside the src directory. This file will contain the list of emojis and their corresponding components. We’ll populate this file later.

Building the Emoji Picker Components

Our emoji picker will consist of a few key components:

  • App Component: The main component that renders the overall structure.
  • EmojiList Component: Displays the list of available emojis.
  • Emoji Component: Represents a single emoji in the list.

1. The App Component

The App component will serve as the parent component, managing the state and rendering the other components. Open App.js and modify it as follows:

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

function App() {
  const [selectedEmoji, setSelectedEmoji] = useState('');

  const handleEmojiClick = (emoji) => {
    setSelectedEmoji(emoji);
  };

  return (
    <div className="App">
      <h1>Emoji Picker</h1>
      <div className="emoji-display">
        {selectedEmoji ? selectedEmoji : 'Click an emoji to select'}
      </div>
      <EmojiList onEmojiClick={handleEmojiClick} />
    </div>
  );
}

export default App;

Here’s what’s happening:

  • Import React and useState: We import the necessary modules.
  • Define State: selectedEmoji is the state variable that holds the currently selected emoji.
  • handleEmojiClick Function: This function updates the selectedEmoji state when an emoji is clicked.
  • Render the Components: We render the EmojiList component and pass the handleEmojiClick function as a prop. We also display the selected emoji.

2. The EmojiList Component

The EmojiList component is responsible for rendering the list of emojis. Open EmojiList.js and add the following code:

import React from 'react';

function EmojiList({ onEmojiClick }) {
  const emojis = [
    '😀', '😂', '😍', '😎', '👍', '👏', '🎉', '🔥', '❤️', '💯',
    '🍕', '🍔', '🍟', '🍦', '🍩', '🎂', '🎁', '🎈', '✨', '🌟',
  ];

  return (
    <div className="emoji-list">
      {emojis.map((emoji, index) => (
        <span key={index} className="emoji" onClick={() => onEmojiClick(emoji)}>
          {emoji}
        </span>
      ))}
    </div>
  );
}

export default EmojiList;

In this component:

  • Import React: We import the React library.
  • Receive Props: We receive the onEmojiClick function as a prop.
  • Define Emojis: An array of emojis is created.
  • Render Emojis: We map through the emojis array and render each emoji as a <span> element. The onClick event is attached to each emoji, calling the onEmojiClick function (passed from the parent component) with the selected emoji.

3. Styling the Components

To make our emoji picker visually appealing, let’s add some basic CSS styling. Create a file named App.css in the src directory and add the following styles:

.App {
  text-align: center;
  font-family: sans-serif;
  padding: 20px;
}

.emoji-display {
  font-size: 2em;
  margin-bottom: 20px;
}

.emoji-list {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
}

.emoji {
  font-size: 2em;
  padding: 10px;
  margin: 5px;
  border: 1px solid #ccc;
  border-radius: 5px;
  cursor: pointer;
}

.emoji:hover {
  background-color: #eee;
}

Import this CSS file into App.js by adding the following line at the top of the file:

import './App.css';

Running the Application

Now that we’ve built the components and added the styling, let’s run the application. Open your terminal, navigate to your project directory (emoji-picker-app), and run the following command:

npm start
# or
yarn start

This will start the development server, and your emoji picker should be accessible in your web browser at http://localhost:3000 (or a similar address). You should see the heading “Emoji Picker”, a display area showing “Click an emoji to select”, and a list of emojis below. Clicking on an emoji will display it in the display area.

Advanced Features and Enhancements

While the basic emoji picker is functional, we can add several enhancements to improve its usability and functionality:

1. Emoji Search

Implement a search feature to filter the emojis based on user input. This will significantly improve the user experience, especially when dealing with a large number of emojis. Here’s how you can add search functionality:

  • Add a search input: In the App component, add an input field for the user to type their search query.
  • Manage search input state: Use the useState hook to manage the search input’s value.
  • Filter emojis: In the EmojiList component, filter the emojis array based on the search input.

Here’s the modified App.js with the search functionality:

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

function App() {
  const [selectedEmoji, setSelectedEmoji] = useState('');
  const [searchQuery, setSearchQuery] = useState('');

  const handleEmojiClick = (emoji) => {
    setSelectedEmoji(emoji);
  };

  const handleSearchChange = (event) => {
    setSearchQuery(event.target.value);
  };

  return (
    <div className="App">
      <h1>Emoji Picker</h1>
      <div className="emoji-display">
        {selectedEmoji ? selectedEmoji : 'Click an emoji to select'}
      </div>
      <input
        type="text"
        placeholder="Search emojis..."
        value={searchQuery}
        onChange={handleSearchChange}
      />
      <EmojiList onEmojiClick={handleEmojiClick} searchQuery={searchQuery} />
    </div>
  );
}

export default App;

And the modified EmojiList.js:

import React from 'react';

function EmojiList({ onEmojiClick, searchQuery }) {
  const emojis = [
    '😀', '😂', '😍', '😎', '👍', '👏', '🎉', '🔥', '❤️', '💯',
    '🍕', '🍔', '🍟', '🍦', '🍩', '🎂', '🎁', '🎈', '✨', '🌟',
  ];

  const filteredEmojis = emojis.filter(emoji =>
    emoji.toLowerCase().includes(searchQuery.toLowerCase())
  );

  return (
    <div className="emoji-list">
      {filteredEmojis.map((emoji, index) => (
        <span key={index} className="emoji" onClick={() => onEmojiClick(emoji)}>
          {emoji}
        </span>
      ))}
    </div>
  );
}

export default EmojiList;

In the updated code, we’ve added a search input in App.js and passed the searchQuery prop to EmojiList. Inside EmojiList, we filter the emojis based on the searchQuery using the filter method. This allows users to quickly find the emojis they need.

2. Emoji Categories

Organize emojis into categories (e.g., smileys, animals, food) to improve navigation and user experience. This involves:

  • Categorizing emojis: Group emojis into different categories.
  • Displaying category tabs: Add a UI element (e.g., tabs or a dropdown) to allow users to select a category.
  • Filtering emojis by category: Render the emojis based on the selected category.

Here’s a simplified example of how you can categorize emojis. First, modify the emojis array in EmojiList.js to include category information. For example, you can change the emojis array to an object that includes the category.

const emojis = [
  { symbol: '😀', category: 'smileys' },
  { symbol: '😂', category: 'smileys' },
  { symbol: '😍', category: 'smileys' },
  { symbol: '😎', category: 'smileys' },
  { symbol: '👍', category: 'symbols' },
  { symbol: '👏', category: 'symbols' },
  { symbol: '🎉', category: 'symbols' },
  { symbol: '🔥', category: 'symbols' },
  { symbol: '❤️', category: 'symbols' },
  { symbol: '💯', category: 'symbols' },
  { symbol: '🍕', category: 'food' },
  { symbol: '🍔', category: 'food' },
  { symbol: '🍟', category: 'food' },
  { symbol: '🍦', category: 'food' },
  { symbol: '🍩', category: 'food' },
  { symbol: '🎂', category: 'food' },
  { symbol: '🎁', category: 'objects' },
  { symbol: '🎈', category: 'objects' },
  { symbol: '✨', category: 'objects' },
  { symbol: '🌟', category: 'objects' },
];

Then, in your App.js, you can add a state variable for the selected category and add a category filter. You can also add a UI element to select the category.

3. Copy to Clipboard

Allow users to copy the selected emoji to the clipboard for easy pasting into other applications. This is a common and useful feature. To implement this:

  • Add a click handler: Attach an event handler to each emoji.
  • Use the Clipboard API: Utilize the navigator.clipboard.writeText() method to copy the emoji to the clipboard.
  • Provide feedback: Give visual feedback to the user when the emoji is copied (e.g., a checkmark or a “Copied!” message).

Here’s how you can modify the EmojiList.js to include the copy to clipboard functionality:

import React from 'react';

function EmojiList({ onEmojiClick, searchQuery }) {
  const emojis = [
    '😀', '😂', '😍', '😎', '👍', '👏', '🎉', '🔥', '❤️', '💯',
    '🍕', '🍔', '🍟', '🍦', '🍩', '🎂', '🎁', '🎈', '✨', '🌟',
  ];

  const filteredEmojis = emojis.filter(emoji =>
    emoji.toLowerCase().includes(searchQuery.toLowerCase())
  );

  const handleEmojiClick = async (emoji) => {
    try {
      await navigator.clipboard.writeText(emoji);
      console.log('Emoji copied to clipboard!');
      onEmojiClick(emoji);
    } catch (err) {
      console.error('Failed to copy emoji: ', err);
    }
  };

  return (
    <div className="emoji-list">
      {filteredEmojis.map((emoji, index) => (
        <span
          key={index}
          className="emoji"
          onClick={() => handleEmojiClick(emoji)}
        >
          {emoji}
        </span>
      ))}
    </div>
  );
}

export default EmojiList;

In this code, we’ve added an async function handleEmojiClick that uses the Clipboard API to copy the emoji to the clipboard. We also added error handling. Remember to update the onClick handler in the <span> element to call the new handleEmojiClick function.

Common Mistakes and Troubleshooting

Here are some common mistakes beginners make when building React applications, along with how to fix them:

  • Incorrect Component Imports: Ensure that you are importing components correctly. Use the correct file paths and ensure the component is exported from the file.
  • State Updates: When updating state, always use the setState function provided by the useState hook. Do not directly modify the state variables.
  • Event Handling: Remember to pass event handlers to the correct elements and to prevent default browser behavior when necessary.
  • Rendering Lists: When rendering lists of items, always use the key prop to provide a unique identifier for each element.
  • CSS Styling Issues: Double-check your CSS class names and make sure your CSS file is correctly imported into your component. Use browser developer tools to inspect the styles and identify any issues.

If you encounter any issues, here are some troubleshooting tips:

  • Check the Console: Open your browser’s developer console (usually by pressing F12) to look for error messages. These messages often provide clues about what went wrong.
  • Inspect the Code: Carefully review your code for typos, incorrect syntax, and logical errors.
  • Use Debugging Tools: Use browser developer tools to step through your code, inspect variables, and identify the source of the problem.
  • Consult Documentation: Refer to the React documentation and online resources for help with specific concepts and features.
  • Ask for Help: Don’t hesitate to ask for help from online communities, forums, or experienced developers.

Summary and Key Takeaways

In this guide, you’ve learned how to build a simple React emoji picker application. You’ve gained practical experience with essential React concepts such as component creation, state management, event handling, and rendering lists. You’ve also learned how to implement advanced features like emoji search and copy-to-clipboard functionality. Building this project has likely enhanced your understanding of React and provided you with a solid foundation for building more complex applications.

Remember that practice is key to mastering React. Continue experimenting with different features, building more complex components, and exploring other React libraries and tools. By consistently practicing and exploring, you’ll become more proficient and confident in your React development skills. This emoji picker is a small step, but it is a significant one towards becoming a proficient React developer. Keep building, keep learning, and enjoy the journey!