Skip to main content

Overview

useSpaceMentions provides autocomplete suggestion logic for #space-slug style mentions in text inputs. It tracks cursor position, detects mention triggers, and fetches matching spaces using debounced search.
Spaces must have a slug set to be mentionable. This hook uses the # trigger by default.

Usage Example

import { useSpaceMentions } from "@replyke/react-js";

function PostEditor() {
  const [content, setContent] = useState("");
  const [cursorPosition, setCursorPosition] = useState(0);
  const inputRef = useRef<HTMLInputElement>(null);

  const {
    isSpaceMentionActive,
    loading,
    spaceMentionSuggestions,
    handleSpaceMentionClick,
    mentions,
  } = useSpaceMentions({
    content,
    setContent,
    cursorPosition,
    isSelectionActive: false,
    focus: () => inputRef.current?.focus(),
  });

  return (
    <div>
      <input
        ref={inputRef}
        value={content}
        onChange={(e) => {
          setContent(e.target.value);
          setCursorPosition(e.target.selectionStart ?? 0);
        }}
      />
      {isSpaceMentionActive && !loading && (
        <ul>
          {spaceMentionSuggestions.map((space) => (
            <li key={space.id} onClick={() => handleSpaceMentionClick(space)}>
              #{space.slug}
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}

Parameters

content
string
required
The current text content of the editor.
setContent
(value: string) => void
required
Setter to update the content when a mention is selected.
focus
() => void
required
Function to re-focus the editor after a mention is selected.
cursorPosition
number
required
Current cursor position in the text.
isSelectionActive
boolean
required
Whether text is currently selected. Disables mention detection during selection.
trigger
string
Character that triggers mention detection. Defaults to "#".
minChars
number
Minimum characters after the trigger before search fires. Defaults to 3.
debounceDelay
number
Milliseconds to wait after the last keystroke before fetching. Defaults to 1000.

Returns

isSpaceMentionActive
boolean
Whether the mention autocomplete is currently active.
loading
boolean
Whether suggestions are being fetched.
spaceMentionSuggestions
Space[]
Matching spaces to display as suggestions.
handleSpaceMentionClick
(space: Space) => void
Call this when a suggestion is selected. Replaces the trigger text with the space slug.
mentions
Mention[]
Accumulated list of all selected mentions (id, slug, type: “space”).
addSpaceMention
(space: Space) => void
Manually add a space to the mentions list.
resetSpaceMentions
() => void
Clear all mention state.