Registry / web-framework / react-mentions

react-mentions

JSON →
library4.4.10jsnpmunverified

React Mentions is a component library providing a flexible, accessible textarea input field with built-in mention functionality, similar to what's found on social media platforms like Twitter or Facebook. The current stable version is 4.4.10, with frequent patch releases addressing bug fixes and minor improvements, and occasional minor versions for new features or refactorings. Its core strength lies in supporting multiple, distinct mention types (e.g., users, tags) within a single input, each configurable with its own trigger character and custom rendering logic for suggestions. It differentiates itself by offering robust control over suggestion display (e.g., portal host, force suggestions above cursor) and comprehensive event callbacks, making it suitable for complex interaction patterns in production applications. It is not a full-featured text editor but focuses specifically on the mentions use case.

npm install react-mentions
INSTALL
IMPORT
SIG · REACT-MENTIONS
R
react-mentions
web-frameworkjavascriptv4.4.10
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

MentionsInput
import { MentionsInput } from 'react-mentions'
const MentionsInput = require('react-mentions').MentionsInput
Primary component for rendering the mentions-enabled textarea.
Mention
import { Mention } from 'react-mentions'
import Mention from 'react-mentions/lib/Mention'
Child component of MentionsInput, used to define specific mention triggers and data sources. Do not import from sub-paths.
MentionsInput (type)
import type { MentionsInputProps } from 'react-mentions'
Import types separately for stricter TypeScript checking.

This quickstart demonstrates a basic React Mentions setup, allowing users to type '@' to trigger suggestions for mentioning predefined users. It includes state management for the input value, a data source function for suggestions, and a custom suggestion renderer, showcasing how to integrate the component into a React application. Basic inline styles are provided for immediate visibility.

import React, { useState, useCallback } from 'react'; import { MentionsInput, Mention } from 'react-mentions'; import './index.css'; // Assuming some basic styling for .mentions, .mention, .suggestions const defaultStyle = { control: { backgroundColor: '#fff', fontSize: 14, fontWeight: 'normal', }, '&multiLine': { control: { minHeight: 63, }, highlighter: { padding: 9, border: '1px solid transparent', }, input: { padding: 9, border: '1px solid silver', }, }, suggestions: { list: { backgroundColor: '#fff', 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: '#cee4e5', }, }, }, }; function MentionsEditor() { const [value, setValue] = useState("Hello @[John Doe](john.doe) and @[Jane Smith](jane.smith)"); const users = [ { id: 'john.doe', display: 'John Doe' }, { id: 'jane.smith', display: 'Jane Smith' }, { id: 'mike.tyson', display: 'Mike Tyson' }, { id: 'alice.wonder', display: 'Alice Wonderland' }, ]; const handleChange = useCallback((event, newValue, newPlainTextValue, mentions) => { setValue(newValue); console.log('New Value:', newValue); console.log('Plain Text:', newPlainTextValue); console.log('Mentions:', mentions); }, []); const fetchUsers = useCallback((query, callback) => { if (!query) return callback(users); const filteredUsers = users.filter(user => user.display.toLowerCase().includes(query.toLowerCase()) ); callback(filteredUsers); }, [users]); return ( <div className="editor-container"> <h2>React Mentions Example</h2> <MentionsInput value={value} onChange={handleChange} style={defaultStyle} // Inline styles for quick demo, recommend external CSS placeholder="Type @ to mention someone..." > <Mention trigger="@" data={fetchUsers} renderSuggestion={(suggestion, search, highlightedDisplay) => ( <div> {highlightedDisplay} </div> )} /> </MentionsInput> <div style={{ marginTop: '20px', border: '1px solid #eee', padding: '10px' }}> <h3>Current Raw Input Value:</h3> <pre>{value}</pre> </div> </div> ); } export default MentionsEditor;
Debug
Known issues
breakingThe `autofocus` attribute was removed from the underlying textarea by default in `v4.4.10`. If your application relied on the input automatically gaining focus upon component mount, you will need to manually manage focus, for example using `inputRef` and `ref.current.focus()` within a `useEffect` hook.
fix
Use the `inputRef` prop on `MentionsInput` to get a ref to the underlying HTML element, and then imperatively call `inputRef.current.focus()` when needed, e.g., in a `useEffect` hook with an empty dependency array for initial mount.
affects: >=4.4.10
gotchaStyling `react-mentions` requires understanding how the component renders its internal structure (a hidden 'highlighter' div mirroring the input content). Directly targeting the input or its container with global styles may lead to misalignments or unexpected visual behavior. It's recommended to use the `style` prop for granular control or carefully scope CSS classes.
fix
Refer to the `react-mentions` documentation for the recommended CSS structure and prop-based styling (e.g., `style` prop for `MentionsInput` and `suggestions`). Avoid overly aggressive global CSS rules that might interfere with its internal layout.
affects: >=1.0.0
gotchaWhen using `suggestionsPortalHost`, ensure that the host element exists in the DOM at the time the `MentionsInput` component mounts, or handle its dynamic availability. Incorrect setup can lead to suggestions not rendering or appearing in unexpected locations.
fix
Provide a valid DOM element to `suggestionsPortalHost` (e.g., `document.body` or a specific `div` element). If the host is dynamically rendered, ensure the `MentionsInput` re-renders or updates its portal when the host becomes available. Consider using `React.createRef` for the host element and passing `hostRef.current`.
affects: >=1.0.0
gotchaThe `onChange` callback provides four arguments: `event`, `newValue`, `newPlainTextValue`, and `mentions`. Developers often only use `newValue` and might miss `newPlainTextValue` which provides the string without markup, or `mentions` which is an array of detected mention objects. Misunderstanding these can lead to incorrect data handling.
fix
Always destructure or access all relevant arguments from the `onChange` callback: `(event, newValue, newPlainTextValue, mentions) => { /* use all here */ }`. Use `newValue` for storing the rich-text content, and `newPlainTextValue` for display purposes where markup is undesirable.
affects: >=1.0.0
gotchaWhen `allowSpaceInQuery` is set to `true`, the suggestion list will remain open even if the user types spaces, which might be an unexpected UX for single-word queries. This prop is primarily for multi-word search queries within the suggestion context.
fix
Only set `allowSpaceInQuery={true}` if your mention data source truly supports multi-word searches (e.g., searching for 'John Doe'). For typical single-name mentions, keep it `false` (default) to close suggestions after a space, which is often more intuitive.
affects: >=1.0.0
Errors
Common errors & fixes
Uncaught Error: MentionsInput needs to have a Mention child
The `MentionsInput` component was rendered without any `Mention` child components. Each `MentionsInput` must define at least one `Mention` to specify triggers and data sources.
fix
Add at least one `<Mention trigger="@" data={yourDataSource} />` child inside your `<MentionsInput>` component.
Error: Invalid prop `data` supplied to `Mention`. Expected an array or a function, but received [object Object].
The `data` prop of a `Mention` component received an object instead of an array of suggestions or a function that fetches suggestions.
fix
Ensure the `data` prop is either an array of objects (e.g., `[{ id: 'id', display: 'Name' }]`) or a function that takes a `query` string and a `callback` function.
ReferenceError: require is not defined (when using import { MentionsInput } from 'react-mentions')
This error typically occurs in environments that only support ES Modules (ESM) when a CommonJS `require()` call is made implicitly by a bundler or explicitly in the code, or when a bundler incorrectly transpiles ESM imports to CJS `require` calls without proper environment configuration.
fix
Ensure your project is configured for ES Modules. If using an older React setup or specific testing frameworks, you might need to adjust Babel/Webpack configurations to correctly handle ESM. For `react-mentions`, always use `import { MentionsInput, Mention } from 'react-mentions'` in modern React projects.
Upgrade
Version history
4.4.10latest on npm
Audit
Dependencies
reactrequiredPeer dependency for the React component to function. Specifies minimum React version.
react-domrequiredPeer dependency for rendering React components to the DOM. Specifies minimum React-DOM version.
Agent activity
4 hits · last 30 days
node
4
Resources
react-mentions — npm install react-mentions · libregistry