Magical text editor with floating mention bubbles and a watchful cat

Mention Magic: Unleashing the Power of react-mentions

The Gray Cat
The Gray Cat

In the vast landscape of React components, react-mentions stands out as a powerful spell in a developer’s arsenal. This enchanting library allows you to weave mention functionality into your textareas, creating an interactive experience reminiscent of social media platforms like Facebook and Twitter. Let’s embark on a magical journey to explore the depths of this component and uncover its secrets.

Unveiling the Magic: Key Features

Before we dive into the incantations, let’s review the magical properties that make react-mentions a must-have in your React spellbook:

  1. Customizable Triggers: Summon mentions with various sigils, be it ’@’ for users or ’#’ for topics.
  2. Flexible Data Sources: Conjure suggestions from static arrays or dynamic async functions.
  3. Styling Flexibility: Dress your mentions in CSS, CSS modules, or inline styles.
  4. Multiple Mention Types: Cast different types of mentions within the same textarea.
  5. Accessibility: Enchant screen readers with proper ARIA attributes.
  6. Single Line Mode: Transform textareas into single-line input fields with a flick of the wand.

Summoning the Component: Installation

To begin our magical practice, we must first summon react-mentions into our project. Choose your preferred summoning circle:

Using npm:

npm install react-mentions --save

Or if you prefer the yarn familiar:

yarn add react-mentions

Casting Your First Spell: Basic Usage

Now that we have react-mentions at our fingertips, let’s cast our first spell. We’ll start with a simple incantation to create a textarea with user mentions:

import React, { useState } from 'react';
import { MentionsInput, Mention } from 'react-mentions';

const MagicalMentions: React.FC = () => {
  const [value, setValue] = useState('');

  const users = [
    { id: 'merlin', display: 'Merlin the Wizard' },
    { id: 'morgana', display: 'Morgana Le Fay' },
    { id: 'arthur', display: 'King Arthur' },
  ];

  const handleChange = (event: any, newValue: string, newPlainTextValue: string, mentions: any[]) => {
    setValue(newValue);
  };

  return (
    <MentionsInput value={value} onChange={handleChange}>
      <Mention
        trigger="@"
        data={users}
        renderSuggestion={(suggestion, search, highlightedDisplay, index, focused) => (
          <div className={`user ${focused ? 'focused' : ''}`}>
            {highlightedDisplay}
          </div>
        )}
      />
    </MentionsInput>
  );
};

export default MagicalMentions;

In this spell, we’ve created a textarea that allows users to mention magical beings by typing ’@‘. The MentionsInput component acts as our magical parchment, while the Mention component defines the rules for our mention enchantment.

Advanced Incantations: Customization

Multitype Mentions

Let’s enhance our spell to include multiple types of mentions. We’ll add hashtags for magical locations:

const MagicalMentionsAdvanced: React.FC = () => {
  const [value, setValue] = useState('');

  const users = [
    { id: 'merlin', display: 'Merlin the Wizard' },
    { id: 'morgana', display: 'Morgana Le Fay' },
  ];

  const locations = [
    { id: 'camelot', display: 'Camelot' },
    { id: 'avalon', display: 'Avalon' },
  ];

  const handleChange = (event: any, newValue: string, newPlainTextValue: string, mentions: any[]) => {
    setValue(newValue);
  };

  return (
    <MentionsInput value={value} onChange={handleChange}>
      <Mention
        trigger="@"
        data={users}
        renderSuggestion={(suggestion, search, highlightedDisplay) => (
          <div className="user-suggestion">{highlightedDisplay}</div>
        )}
      />
      <Mention
        trigger="#"
        data={locations}
        renderSuggestion={(suggestion, search, highlightedDisplay) => (
          <div className="location-suggestion">{highlightedDisplay}</div>
        )}
      />
    </MentionsInput>
  );
};

Asynchronous Suggestions

For more dynamic enchantments, we can summon suggestions asynchronously:

const AsyncMagicalMentions: React.FC = () => {
  const [value, setValue] = useState('');

  const fetchUsers = (query: string, callback: (users: any[]) => void) => {
    setTimeout(() => {
      const users = [
        { id: 'merlin', display: 'Merlin the Wizard' },
        { id: 'morgana', display: 'Morgana Le Fay' },
      ].filter(user => user.display.toLowerCase().includes(query.toLowerCase()));
      callback(users);
    }, 1000); // Simulating API call
  };

  return (
    <MentionsInput value={value} onChange={(event, newValue) => setValue(newValue)}>
      <Mention
        trigger="@"
        data={fetchUsers}
        renderSuggestion={(suggestion) => <div>{suggestion.display}</div>}
      />
    </MentionsInput>
  );
};

Styling Your Mentions

To give your mentions a magical appearance, you can use inline styles or CSS classes:

const StyledMagicalMentions: React.FC = () => {
  const [value, setValue] = useState('');

  const users = [
    { id: 'merlin', display: 'Merlin the Wizard' },
    { id: 'morgana', display: 'Morgana Le Fay' },
  ];

  const mentionStyle = {
    backgroundColor: '#d1c4e9',
    padding: '2px 4px',
    borderRadius: '3px',
    color: '#4527a0',
    fontWeight: 'bold',
  };

  return (
    <MentionsInput
      value={value}
      onChange={(event, newValue) => setValue(newValue)}
      style={{
        control: {
          fontSize: 16,
          lineHeight: 1.5,
        },
        input: {
          margin: 0,
          padding: 5,
          border: '1px solid #ccc',
        },
        highlighter: {
          padding: 5,
        },
        suggestions: {
          list: {
            backgroundColor: 'white',
            border: '1px solid rgba(0,0,0,0.15)',
            fontSize: 14,
          },
          item: {
            padding: '5px 15px',
            borderBottom: '1px solid rgba(0,0,0,0.15)',
            '&focused': {
              backgroundColor: '#e8e8e8',
            },
          },
        },
      }}
    >
      <Mention
        trigger="@"
        data={users}
        renderSuggestion={(suggestion) => <div>{suggestion.display}</div>}
        style={mentionStyle}
      />
    </MentionsInput>
  );
};

Conclusion: Mastering the Art of Mentions

As we conclude our magical journey through the realm of react-mentions, you now possess the knowledge to enchant your textareas with powerful mention capabilities. From basic implementations to advanced customizations, this versatile component offers a world of possibilities for enhancing user interactions in your React applications.

Remember, the true power of react-mentions lies in its flexibility and ease of use. Experiment with different triggers, data sources, and styling options to create mention experiences that are truly magical for your users.

As you continue your quest in React development, consider exploring related enchantments such as form handling with Uniforms or enhancing your UI with Chakra UI. These powerful tools can complement your newfound mention abilities and further elevate your React sorcery.

May your textareas be ever interactive and your mentions always relevant. Happy coding, and may the magic of React be with you!