mentis

onChange Callback

The onChange callback in Mentis provides you with both the display text and structured mention data. This allows you to access the actual mention values for processing, validation, or API calls.

Key Difference:

  • value: Shows mention labels (what users see, e.g., "@Alice")
  • dataValue: Shows mention values (actual data, e.g., "user_123")

Callback Signature

The onChange callback receives a MentionData object:

type MentionData = {
  value: string; // The text as displayed in the input (shows mention labels)
  dataValue: string; // The text with mention values (shows actual data)
  mentions: Array<{
    label: string; // The display label of the mention
    value: string; // The actual value of the mention
    startIndex: number; // Position where the mention starts in the text
    endIndex: number; // Position where the mention ends in the text
  }>;
};

Basic Usage

import { MentionInput, type MentionData } from "mentis";

function App() {
  const [mentionData, setMentionData] = useState<MentionData | null>(null);

  const handleChange = (newValue: MentionData) => {
    setMentionData(newValue);

    // Access mention values
    const mentionValues = newValue.mentions.map((mention) => mention.value);
    console.log("Mention values:", mentionValues);
  };

  return (
    <MentionInput
      options={[
        { label: "Alice", value: "user_123" },
        { label: "Bob", value: "user_456" },
      ]}
      onChange={handleChange}
    />
  );
}

Example: Processing Mentions

Here's how you might use the structured data to process mentions:

const handleChange = (newValue: MentionData) => {
  // value shows what the user sees (e.g., "Hello @Alice and @Bob")
  console.log("Display text:", newValue.value);

  // dataValue shows the actual values (e.g., "Hello user_123 and user_456")
  console.log("Data value:", newValue.dataValue);

  // Extract user IDs for API calls
  const userIds = newValue.mentions.map((mention) => mention.value);

  // Send to API
  if (userIds.length > 0) {
    notifyUsers(userIds);
  }

  // Validate mentions
  const validMentions = newValue.mentions.filter((mention) =>
    mention.value.startsWith("user_")
  );

  if (validMentions.length !== newValue.mentions.length) {
    console.warn("Some mentions are invalid");
  }
};

When You Get Structured Data

The onChange callback always provides structured MentionData when:

  • A mention is selected from the dropdown
  • Text is pasted that contains mentions
  • Mentions are auto-converted (when autoConvertMentions is true)
  • The input content changes (even when empty or with only plain text)