React Component: Custom Popup Menu for Selected Text

In this tutorial, we’ll explore how to create a custom popup menu React component that appears when text is selected. This feature can enhance the user experience by offering context-specific actions or information, empowering users with more control and convenience.

Complete code for this React component is available in github repository.

Table of Contents:

Prerequisites:

To follow along with this tutorial, you should have a basic understanding of React and JavaScript.

Setting up the Project:

Create a new React project by running the following command:

npx create-react-app popup-react-component

After successful react project creation, navigate into the popup-react-component directory by running the following command:

cd popup-react-component

Go ahead and remove auto generated files like App.css, Index.css and logo.svg

Implementing the CustomPopupMenu Component:

Let us define the CustomPopupMenu component, which will handle the logic and rendering of the custom popup menu.

Create a new file called CustomPopupMenu.js in the src directory and add the following code to the CustomPopupMenu.js file.

import React, { useEffect, useState } from 'react';

const CustomPopupMenu = () => {
  const [showMenu, setShowMenu] = useState(false);
  const [menuPosition, setMenuPosition] = useState({ x: 0, y: 0 });

  useEffect(() => {
    const handleSelection = () => {
      const selection = window.getSelection();
      if (selection && selection.toString()) {
        const range = selection.getRangeAt(0).getBoundingClientRect();
        setMenuPosition({
          x: range.x + range.width / 2,
          y: range.y - 30, // Adjust the y-offset to position the menu correctly
        });
        setShowMenu(true);
      } else {
        setShowMenu(false);
      }
    };

    document.addEventListener('mouseup', handleSelection);

    return () => {
      document.removeEventListener('mouseup', handleSelection);
    };
  }, []);

  return (
    <div>
      {showMenu && (
        <div
          style={{
            position: 'absolute',
            left: menuPosition.x,
            top: menuPosition.y,
            background: '#ffffff',
            boxShadow: '0px 1px 5px rgba(0, 0, 0, 0.2)',
            padding: '10px',
            borderRadius: '4px',
          }}
        >
          <ul style={{ listStyleType: 'none', margin: 0, padding: 0 }}>
            <li
              style={{
                padding: '5px 0',
                borderBottom: '1px solid #eaeaea',
              }}
            >
              Option 1
            </li>
            <li
              style={{
                padding: '5px 0',
                borderBottom: '1px solid #eaeaea',
              }}
            >
              Option 2
            </li>
            <li style={{ padding: '5px 0' }}>Option 3</li>
          </ul>
        </div>
      )}
    </div>
  );
};

export default CustomPopupMenu;

In the CustomPopupMenu component, we make use of React hooks. We initialize the showMenu state variable as false, which determines whether the popup menu should be displayed. The menuPosition state variable stores the position of the popup menu.

We then use the useEffect hook to add an event listener for the mouseup event. When the user releases the mouse button after selecting text, the handleSelection function is called. It checks if there is a selected text and calculates the position of the selection range using getBoundingClientRect(). If there is a selection, the showMenu state is set to true, and the menuPosition is updated with the calculated position. If there is no selection, the showMenu state is set to false.

Inside the JSX, we conditionally render the popup menu by checking the showMenu state. If it’s true, we render a div element at the specified menuPosition. This div represents the popup menu and contains a simple unordered list with some example options.

For styling, we’ve added inline styles to the popup menu and its list items. The menu’s background color is set to #ffffff (white), and it has a box shadow to give it a raised effect. The padding and border radius are adjusted to provide some spacing and rounded corners.

The list items have a padding of 5px vertically and 0 horizontally. The first two list items have a bottom border of 1px solid #eaeaea to create a separator effect between the options.

Feel free to adjust these styles according to your design preferences to create a visually appealing custom popup menu.

Using the CustomPopupMenu Component:

Now lets integrate the CustomPopupMenu component into our application.

Open the src/App.js file and import the CustomPopupMenu component at the top of the file.

Inside the App component, add the CustomPopupMenu component below the existing content. Our App.js file should look like below:

import './App.css';
import CustomPopupMenu from './CustomPopupMenu';

function App() {
  return (
    <div>
      <h1>My App</h1>
      <p>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse
        varius nibh eu hendrerit dictum. Sed at vestibulum nisi. Sed
        suscipit magna ac tortor rutrum faucibus. Quisque aliquet faucibus
        nibh, ac rutrum tortor aliquam et. Duis gravida tincidunt feugiat.
        Donec id sapien tincidunt, interdum felis nec, facilisis nulla. Cras
        pharetra euismod mi, ut consequat urna vestibulum eu. Sed finibus
        ligula ac dapibus consequat. Proin vel sollicitudin purus, at gravida
        risus. In luctus risus mauris, ut consequat massa viverra ut. Donec
        ultricies facilisis nisl in eleifend. Curabitur quis mi et nibh
        volutpat dignissim. Suspendisse non congue tortor, ac venenatis nisi.
        Aliquam commodo, justo non ultrices blandit, mi metus pulvinar urna,
        a condimentum elit est a ligula.
      </p>
      <CustomPopupMenu />
    </div>
  );
}

export default App;

Save the file and start the development server:

npm start

Open your browser and navigate to http://localhost:3000. You should see the text content rendered, and when you select a portion of the text, a custom popup menu should appear at the selected position.

Select text popup react component

In this tutorial, we’ve explored how to create a custom popup menu in React that appears when text is selected. We leveraged React hooks and event listeners to track the selected text and calculate its position. By using conditional rendering, we displayed a popup menu with options tailored to the selected text. You can customize the menu’s appearance and content to suit your specific needs and enhance the user experience in your React applications.


Discover More about how to create Instagram like carousel React Component in other post.

2 Responses

Leave a Reply

Your email address will not be published. Required fields are marked *

Post comment