{"id":11750,"library":"react-mentions","title":"React Mentions Input Component","description":"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.","status":"active","version":"4.4.10","language":"javascript","source_language":"en","source_url":"https://github.com/signavio/react-mentions","tags":["javascript","react","mentions","react-component"],"install":[{"cmd":"npm install react-mentions","lang":"bash","label":"npm"},{"cmd":"yarn add react-mentions","lang":"bash","label":"yarn"},{"cmd":"pnpm add react-mentions","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Peer dependency for the React component to function. Specifies minimum React version.","package":"react","optional":false},{"reason":"Peer dependency for rendering React components to the DOM. Specifies minimum React-DOM version.","package":"react-dom","optional":false}],"imports":[{"note":"Primary component for rendering the mentions-enabled textarea.","wrong":"const MentionsInput = require('react-mentions').MentionsInput","symbol":"MentionsInput","correct":"import { MentionsInput } from 'react-mentions'"},{"note":"Child component of MentionsInput, used to define specific mention triggers and data sources. Do not import from sub-paths.","wrong":"import Mention from 'react-mentions/lib/Mention'","symbol":"Mention","correct":"import { Mention } from 'react-mentions'"},{"note":"Import types separately for stricter TypeScript checking.","symbol":"MentionsInput (type)","correct":"import type { MentionsInputProps } from 'react-mentions'"}],"quickstart":{"code":"import React, { useState, useCallback } from 'react';\nimport { MentionsInput, Mention } from 'react-mentions';\nimport './index.css'; // Assuming some basic styling for .mentions, .mention, .suggestions\n\nconst defaultStyle = {\n  control: {\n    backgroundColor: '#fff',\n    fontSize: 14,\n    fontWeight: 'normal',\n  },\n  '&multiLine': {\n    control: {\n      minHeight: 63,\n    },\n    highlighter: {\n      padding: 9,\n      border: '1px solid transparent',\n    },\n    input: {\n      padding: 9,\n      border: '1px solid silver',\n    },\n  },\n  suggestions: {\n    list: {\n      backgroundColor: '#fff',\n      border: '1px solid rgba(0,0,0,0.15)',\n      fontSize: 14,\n    },\n    item: {\n      padding: '5px 15px',\n      borderBottom: '1px solid rgba(0,0,0,0.15)',\n      '&focused': {\n        backgroundColor: '#cee4e5',\n      },\n    },\n  },\n};\n\nfunction MentionsEditor() {\n  const [value, setValue] = useState(\"Hello @[John Doe](john.doe) and @[Jane Smith](jane.smith)\");\n\n  const users = [\n    { id: 'john.doe', display: 'John Doe' },\n    { id: 'jane.smith', display: 'Jane Smith' },\n    { id: 'mike.tyson', display: 'Mike Tyson' },\n    { id: 'alice.wonder', display: 'Alice Wonderland' },\n  ];\n\n  const handleChange = useCallback((event, newValue, newPlainTextValue, mentions) => {\n    setValue(newValue);\n    console.log('New Value:', newValue);\n    console.log('Plain Text:', newPlainTextValue);\n    console.log('Mentions:', mentions);\n  }, []);\n\n  const fetchUsers = useCallback((query, callback) => {\n    if (!query) return callback(users);\n    const filteredUsers = users.filter(user =>\n      user.display.toLowerCase().includes(query.toLowerCase())\n    );\n    callback(filteredUsers);\n  }, [users]);\n\n  return (\n    <div className=\"editor-container\">\n      <h2>React Mentions Example</h2>\n      <MentionsInput\n        value={value}\n        onChange={handleChange}\n        style={defaultStyle} // Inline styles for quick demo, recommend external CSS\n        placeholder=\"Type @ to mention someone...\"\n      >\n        <Mention\n          trigger=\"@\"\n          data={fetchUsers}\n          renderSuggestion={(suggestion, search, highlightedDisplay) => (\n            <div>\n              {highlightedDisplay}\n            </div>\n          )}\n        />\n      </MentionsInput>\n      <div style={{ marginTop: '20px', border: '1px solid #eee', padding: '10px' }}>\n        <h3>Current Raw Input Value:</h3>\n        <pre>{value}</pre>\n      </div>\n    </div>\n  );\n}\n\nexport default MentionsEditor;\n","lang":"typescript","description":"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."},"warnings":[{"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.","message":"The `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.","severity":"breaking","affected_versions":">=4.4.10"},{"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.","message":"Styling `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.","severity":"gotcha","affected_versions":">=1.0.0"},{"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`.","message":"When 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.","severity":"gotcha","affected_versions":">=1.0.0"},{"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.","message":"The `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.","severity":"gotcha","affected_versions":">=1.0.0"},{"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.","message":"When `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.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Add at least one `<Mention trigger=\"@\" data={yourDataSource} />` child inside your `<MentionsInput>` component.","cause":"The `MentionsInput` component was rendered without any `Mention` child components. Each `MentionsInput` must define at least one `Mention` to specify triggers and data sources.","error":"Uncaught Error: MentionsInput needs to have a Mention child"},{"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.","cause":"The `data` prop of a `Mention` component received an object instead of an array of suggestions or a function that fetches suggestions.","error":"Error: Invalid prop `data` supplied to `Mention`. Expected an array or a function, but received [object Object]."},{"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.","cause":"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.","error":"ReferenceError: require is not defined (when using import { MentionsInput } from 'react-mentions')"}],"ecosystem":"npm"}