A React component that let's you mention people in a textarea like you are used to on Facebook or Twitter.

Last update: Jun 18, 2022

React Mentions

CircleCI codecov npm package semantic-release

A React component that let's you mention people in a textarea like you are used to on Facebook or Twitter.

Used in production at Signavio, State, Snips, Swat.io, GotDone, Volinspire, Marvin, Timely, GuideFitter, Evite, Publer, Kontentino, and you?

Getting started

Install the react-mentions package via npm:

npm install react-mentions --save

Or yarn:

yarn add react-mentions

The package exports two React components for rendering the mentions textarea:

import { MentionsInput, Mention } from 'react-mentions'

MentionsInput is the main component rendering the textarea control. It takes one or multiple Mention components as its children. Each Mention component represents a data source for a specific class of mentionable objects, such as users, template variables, issues, etc.

Example:

">
<MentionsInput value={this.state.value} onChange={this.handleChange}>
  <Mention
    trigger="@"
    data={this.props.users}
    renderSuggestion={this.renderUserSuggestion}
  />
  <Mention
    trigger="#"
    data={this.requestTag}
    renderSuggestion={this.renderTagSuggestion}
  />
</MentionsInput>

You can find more examples here: demo/src/examples

Configuration

The MentionsInput supports the following props for configuring the widget:

Prop name Type Default value Description
value string '' The value containing markup for mentions
onChange function (event, newValue, newPlainTextValue, mentions) empty function A callback that is invoked when the user changes the value in the mentions input
singleLine boolean false Renders a single line text input instead of a textarea, if set to true
onBlur function (event, clickedSuggestion) empty function Passes true as second argument if the blur was caused by a mousedown on a suggestion
allowSpaceInQuery boolean false Keep suggestions open even if the user separates keywords with spaces.
suggestionsPortalHost DOM Element undefined Render suggestions into the DOM in the supplied host element.
inputRef React ref undefined Accepts a React ref to forward to the underlying input element
allowSuggestionsAboveCursor boolean false Renders the SuggestionList above the cursor if there is not enough space below
a11ySuggestionsListLabel string '' This label would be exposed to screen readers when suggestion popup appears

Each data source is configured using a Mention component, which has the following props:

Prop name Type Default value Description
trigger regexp or string '@' Defines the char sequence upon which to trigger querying the data source
data array or function (search, callback) null An array of the mentionable data entries (objects with id & display keys, or a filtering function that returns an array based on a query parameter
renderSuggestion function (entry, search, highlightedDisplay, index, focused) null Allows customizing how mention suggestions are rendered (optional)
markup string '@[__display__](__id__)' A template string for the markup to use for mentions
displayTransform function (id, display) returns display Accepts a function for customizing the string that is displayed for a mention
regex RegExp automatically derived from markup pattern Allows providing a custom regular expression for parsing your markup and extracting the placeholder interpolations (optional)
onAdd function (id, display, startPos, endPos) empty function Callback invoked when a suggestion has been added (optional)
appendSpaceOnAdd boolean false Append a space when a suggestion has been added (optional)

If a function is passed as the data prop, that function will be called with the current search query as first, and a callback function as second argument. The callback can be used to provide results asynchronously, e.g., after fetch requests. (It can even be called multiple times to update the list of suggestions.)

Styling

react-mentions supports css, css modules, and inline styles. It is shipped with only some essential inline style definitions and without any css. Some example inline styles demonstrating how to customize the appearance of the MentionsInput can be found at demo/src/examples/defaultStyle.js.

If you want to use css, simply assign a className prop to MentionsInput. All DOM nodes rendered by the component will then receive class name attributes that are derived from the base class name you provided.

If you want to avoid global class names and use css modules instead, you can provide the automatically generated class names as classNames to the MentionsInput. See demo/src/examples/CssModules.js for an example of using react-mentions with css modules.

You can also assign className and style props to the Mention elements to define how to highlight the mentioned words.

Testing

Due to react-mentions' internal cursor tracking it is not good enough to simulate the editing of the textarea value using ReactTestUtils.Simulate.change. We recommend using @testing-library/user-event for a realistic simulation of events as they would happen in the browser as the user interacts the textarea.

Contributing

Spawn a development server with an example page and module hot loading all set up:

npm start

Update the examples page on Github Pages:

npm run pages-publish

GitHub

https://github.com/signavio/react-mentions/
Comments
  • 1. Add optional bottom guard for rendering suggestion list

    Adds an optional prop allowSuggestionsAboveCursor that if set to true, the suggestion list will render above the cursor if there is not enough space underneath.

    Repro steps: I came across this problem because the text input with react-mentions for my app is positioned in the bottom-right corner of the screen. Using the suggestions portal, if the user attempted to @ mention something, the suggestions list will open up underneath the cursor, making the list unusable since it would be cut off by the bottom of the screen. I tried to position it absolutely like the advanced example, but then it would get cut off by the right side of the screen if I tried to @ mention multiple things on the same line since the text input is on the bottom-right and the absolute positioning will make the right guard useless.

    I added the allowSuggestionsAboveCursor prop and code that checks the prop and the spacing around the component to see if there is enough space to render the suggestion list underneath the cursor (the default way), and if there is not enough space underneath but enough space above, the list will render above the cursor (by adjusting the top) given the prop is set to true.

    The PR resolves the whole issue since I added checks for both the suggestionsPortal mode and the default mode. I followed closely the coding convention of the file. I did not add tests since I could not find any examples in the existing tests that tests rendering positions.

    The changes should not affect other parts of the code base since the added prop makes it opt-in. I did not add any extra test files or set up. Please test that the rendering behavior is as expected.

    Reviewed by hyan7 at 2019-07-05 21:33
  • 2. onRemove function for Mention component?

    Hi,

    Have you considered adding a way to detect when a mention gets removed?

    Right now, I'm using onAdd to keep a list of tagIds for database associations, but I'd like to avoid associating tags that were added, but later removed. Ideas?

    PS: Thanks again for an awesome plugin!

    Reviewed by t1mmen at 2016-03-29 20:25
  • 3. feat: Support multiple markup patterns

    Implements #300

    BREAKING CHANGE: Moved markup, displayTransform, and regex props from MentionsInput to Mention component

    BREAKING CHANGE: The __type__ placeholder is no longer supported in the markup pattern. Also, the Mention component's type prop is no longer required.

    Reviewed by jfschwarz at 2019-02-21 14:28
  • 4. Warning: React.findDOMNode is deprecated. Please use ReactDOM.findDOMNode from require('react-dom') instead.

    Hi, I'm getting this warning here:

      updateSuggestionsPosition: function updateSuggestionsPosition() {
        if (!this.refs.caret || !this.refs.suggestions) return;
    
        var containerEl = this.refs.container;
        var caretEl = this.refs.caret;
        var suggestionsEl = React.findDOMNode(this.refs.suggestions); // <<<<<< Warning here.
        var highligherEl = this.refs.highlighter;
        if (!suggestionsEl) return;
    
        var leftPos = caretEl.offsetLeft - highligherEl.scrollLeft;
        // guard for mentions suggestions list clipped by right edge of window
        if (leftPos + suggestionsEl.offsetWidth > containerEl.offsetWidth) {
          suggestionsEl.style.right = "0px";
        } else {
          suggestionsEl.style.left = leftPos + "px";
        }
        suggestionsEl.style.top = caretEl.offsetTop - highligherEl.scrollTop + "px";
      },
    

    Can potentially be fixed by using:

        var suggestionsEl = ReactDOM.findDOMNode(this.refs.suggestions);
    
    Reviewed by pzavolinsky at 2015-10-28 17:34
  • 5. Possible to render in Shadow DOM?

    There seems to be a problem when using this package in the Shadow DOM and I'm curious if it's possible to use react-mentions when your react app is rendered in the Shadow DOM, or if it's not currently supported.

    The problem comes down to the onChange event is not being dispatched for the Mention component, whereas in the normal DOM the onChange event is fired and brings up the supplied data options without problem.

    There are issues with events not working as expected with React in the Shadow DOM, however the react-shadow package takes care of those issues and I've verified that the events are being dispatched correctly for other components and DOM elements - however with react-shadow (and other mention-based packages as well) the onChange event is not seen.

    Reviewed by awwester at 2017-08-08 00:42
  • 6. Add failing test for custom regex that contains trigger

    What did you change (functionally and technically)?

    I want to add mentions to my input which show @max and also send @max to the server. I thought the custom regexp feature introduced in #255 would help me achieve that, but it only seems to work if the custom regex does not include the trigger.

    I would love for this to work, any ideas what the necessary change would be?

    Reviewed by mxstbr at 2019-01-28 09:17
  • 7. the mention color not obvious

    Steps to reproduce:

    the mention color not good and not obvios even when i put text sahdow

    Expected behaviour: send prop color

    Observed behaviour:

    Workaround:

    Reviewed by Yussur90 at 2019-10-24 13:13
  • 8. chore: Remove lodash

    Fixes #284

    Removed lodash dependency. Replaced with simplified util functions. Some of which were taken straight from @goenning 's PR. Included tests. Instead of using _.values, used Object.values.

    Reviewed by matthewtmoran at 2019-06-24 20:38
  • 9. Open suggestions above cursor

    I would be great if the suggestions box will be opened above the cursor if there are not enough space below.

    Example: We have a comment stream with a "insert comment" form at the bottom of the body. if a user want to add a mention, the suggestions-box opens out of the body.

    Reviewed by maxnowack at 2015-09-22 14:06
  • 10. Cursor position jumps back on white spaces in Mobile Chrome on Android

    Typing in any MentionsInput field in the Chrome browser on Android jumps the cursor position backwards on white spaces, making it impossible to type free form text.

    Steps to reproduce:

    1. Open latest Chrome (43.0.2357.93, updated 10 Jun) on an Android phone (tested on Nexus 5, Android 5.1)
    2. Go to http://effektif.github.io/react-mentions/
    3. Focus any of the example input fields and start typing a sentence

    Expected: the cursor position stays at the end of whatever you've typed Actual: the cursor jumps back (typically by the previous words' length) and breaks the typing flow

    Reviewed by mihai at 2015-06-11 15:18
  • 11. Cannot install. Getting 404 error

    Steps to reproduce:

    1. run 'npm install react-mentions'

    Expected behaviour: Package should install without errors.

    Observed behaviour: npm ERR! code E404 npm ERR! 404 Not Found - GET https://registry.npmjs.org/react-mentions/-/react-mentions-4.4.1.tgz npm ERR! 404 npm ERR! 404 '[email protected]' is not in the npm registry. npm ERR! 404 You should bug the author to publish it (or use the name yourself!) npm ERR! 404 npm ERR! 404 Note that you can also install from a npm ERR! 404 tarball, folder, http url, or git url.

    Reviewed by hesperanca at 2022-05-28 21:19
  • 12. 4.4.2 doesn't seem to include the 4.4.0 changes

    4.4.0 was supposed to include these changes to make copy & paste work with disabled inputs: https://github.com/signavio/react-mentions/pull/570/files#diff-b93f5486e33dabca047d7813cfda3b850e21823fdb3dae6ad48f6b2f7662ba8eL403-R406

    Observed behaviour:

    4.4.2 doesn't seems to include these changes in the node_modules package. The function still gets the selection from the state:

        key: "saveSelectionToClipboard",
        value: function saveSelectionToClipboard(event) {
          var _this$state4 = this.state,
              selectionStart = _this$state4.selectionStart,
              selectionEnd = _this$state4.selectionEnd;
    

    @atilafassina maybe something went wrong manually releasing the package?

    Expected behaviour:

    When I do yarn build on my machine I get the following reuslt:

        key: "saveSelectionToClipboard",
        value: function saveSelectionToClipboard(event) {
          // use the actual selectionStart & selectionEnd instead of the one stored
          // in state to ensure copy & paste also works on disabled inputs & textareas
          var selectionStart = this.inputElement.selectionStart;
          var selectionEnd = this.inputElement.selectionEnd;
    
    Reviewed by nikgraf at 2022-06-01 12:51
  • 13. ChainAlert: npm package release (4.4.2) has no matching tag in this repo

    Dear react-mentions maintainers, Thank you for your contribution to the open-source community.

    This issue was automatically created to inform you a new version (4.4.2) of react-mentions was published without a matching tag in this repo.

    As part of our efforts to fight software supply chain attacks, we would like to verify this release is known and intended, and not a result of an unauthorized activity.

    If you find this behavior legitimate, kindly close and ignore this issue. Read more

    badge

    Reviewed by chainalert-bot at 2022-05-30 19:15
  • 14. Copy/pasting mentions from a disabled textarea not working in firefox

    Steps to reproduce:

    1. Create a Mention that passes a disabled prop into the MentionInput (I suggest using the one in the demo example CutCopyPaste.js
    2. In firefox, try copying a mention from the disabled textarea to another (non-disabled) textarea

    Expected behaviour: Mention is pasted along with the text

    Observed behaviour: Only text is pasted

    Workaround: N/A

    Reviewed by Sigrsig at 2022-05-24 13:13
  • 15. return full selected option instead of id and display only

    Fixes #ABC

    What did you change (functionally and technically)?

    Checklist (remove this list before you submit the PR)

    • Are there tests for the new code? no
    • Does the code comply to our code conventions? yes
    • Does the PR resolve the whole issue? yes

    Additional review hints (remove this list before you submit the PR)

    • Besides the code review, what should the reviewer test? review mentionInput component
    • Are there any edge cases? no
    • Do you have any test files or test set-up? no
    • Could your changes cause side effects elsewhere in the code base? no
    Reviewed by AhmedElshaf3i at 2022-05-18 18:02
  • 16. Debouncer support to async api calls

    Steps to reproduce:

          const [usersList, setUsersList] = useState([]);
          onChange = ()=> {
            subject.next();
          });
    
          subject.pipe(debounce).subscribe(()=>{
           api.subscribe((response)=> setusersList(response));
          });
    
    
          <MentionsInput
            value={value}
            onChange={onChange}
            style={defaultStyle}
            placeholder="Mention any Github user by typing `@` followed by at least one char"
            a11ySuggestionsListLabel={"Suggested Github users for mention"}
          >
            <Mention
              displayTransform={login => `@${login}`}
              trigger="@"
              data={usersList}
              style={defaultMentionStyle}
            />
          </MentionsInput>
    
    

    Expected behaviour: Dropdown should update after setUsersList()

    Observed behaviour: Not responding to setUsersList()

    Workaround: Please propagate props

    Reviewed by 9thQuadrant at 2022-05-18 10:17
React Input Format & Mask, tiny (≈800b) component to transform any input component into formatted or masked input. Supports number, date, phone, currency, credit card, etc

RIFM - React Input Format & Mask Is a tiny (≈ 800b) component (and hook) to transform any input component into formatted or masked input. Demo Highlig

Jun 22, 2022
Input masking component for React. Made with attention to UX.

react-input-mask Input masking component for React. Made with attention to UX. This is a development branch for version 3.0. For the latest stable ver

Jun 22, 2022
Masked input React component

MaskedInput A React component for input masking, built on top of inputmask-core. Live Demo Install npm npm install react-maskedinput --save Browser

Jun 6, 2022
React component for entering and validating PIN code.
React component for entering and validating PIN code.

React component for entering and validating PIN code.

Jun 8, 2022
React Currency Input Field Component
React Currency Input Field Component

React Currency Input Field Component

Jun 25, 2022
A react component for digit inputs

A react component for digit inputs. It might be very useful to get SMS codes from user on two factor authentications and in many other scenarios when you need get an numerical input from user digit by digit.

Feb 23, 2021
Headless phone number input component for React. Because phone numbers are hard.

React Headless Phone Input A headless phone number input component built for usability. Phone numbers are hard. Users expect to be able to enter phone

Mar 29, 2022
A fully customizable, one-time password input component for the web built with React.
A fully customizable, one-time password input component for the web built with React.

react-otp-input A fully customizable, one-time password input component for the web built with React. Live Demo CodeSandbox Installation To install th

Jun 13, 2022
A React component that decorates it's children with mouse/touch position tracking, a status toggle fired by click/gesture events, and more.

A React component that decorates it's children with mouse/touch position tracking, a status toggle fired by click/gesture events, and more.

Jun 17, 2022
React component that handles csv file input and its parsing

react-csv-reader React component that handles csv file input. It handles file input and returns its content as a matrix. Docs: nzambello.github.io/rea

May 24, 2022
React component for international phone number input
React component for international phone number input

react-phone-number-input International phone number input for React. See Demo Install npm install react-phone-number-input --save If you're not us

Jun 16, 2022
Time-input - A keyboard friendly react component for capturing time

time-input A keyboard friendly react component for capturing time features small UI surface area (just a form input) keyboard friendly (can type times

Jun 6, 2019
A fully customizable, one-time password input component for the web built with React

block-code A fully customizable, one-time password input component for the web built with React Live demo Highlights Easy to use Fully customizable Re

Mar 24, 2022
International phone number input component for react

Welcome to react-contact-number-input ?? International phone number input component for react Install npm install react-contact-number-input Author ??

Apr 12, 2022
A ReactJS component that allows for multiple text field input, built using the FluentUI library
A ReactJS component that allows for multiple text field input, built using the FluentUI library

A ReactJS component that allows for multiple text field input, built using the FluentUI library

Sep 22, 2021
A ReactJS input component that manages multiple languages
A ReactJS input component that manages multiple languages

React-translatable-input A ReactJS input component that manages multiple languages. $ npm install --save react-translatable-input Demo http://belkalab

Jun 17, 2022
A React Hook & Container to help with payment card input fields.
A React Hook & Container to help with payment card input fields.

React Payment Inputs A React Hook & Container to help with payment card input fields. React Payment Inputs Demos Requirements Installation Usage With

Jun 7, 2022
Input mask for React, Angular, Ember, Vue, & plain JavaScript
Input mask for React, Angular, Ember, Vue, & plain JavaScript

⚠️ This library is not maintained. Pull-requests and issues are not monitored. Alternatives to text-mask include: https://github.com/uNmAnNeR/imaskjs

Jun 27, 2022
A numpad for number, date and time, built with and for React.

React numpad A numpad for number, date and time, built with and for React. It's written with the extensibility in mind. The idea of this project is to

May 22, 2022