In react, trix editor doesnt support functionality of @mention I have made here a simple version of it here below can anyone help me and try to add filter in it and use of arrow keys because trix doesn't support onKeyUp and onKeyDown
states and refrences
// jsx
const [trixData, setTrixData] = useState({ name: '', pageData: { text: '', html: '' } })
const [mentions, setMentions] = useState([])
const [showDropdown, setShowDropdown] = useState(false)
const [mentionSuggestions, setMentionSuggestions] = useState([])
const trixEditorRef = useRef(null)
handleEditorChange is onChange method used for trixEditor
const handleEditorChange = (html, text) => {
setTrixData((prev) => ({
...prev,
pageData: { text: text, html: html },
}))
const cursorPosition = trixEditorRef.current.editor.getSelectedRange()[0]
const typedChar = cursorPosition > 0 ? text[cursorPosition - 1] : ''
if (typedChar === '@') {
setShowDropdown(true)
// const typedName = text.substring(cursorPosition)
// const matchingAdmins = mentions.filter((adminName) =>
// adminName.toLowerCase().startsWith(typedName.toLowerCase()),
// )
setMentionSuggestions(mentions)
} else {
setShowDropdown(false)
setMentionSuggestions([])
}
}
handleMentionSelect if the function responsible for adding @mention in trixEditor field
const handleMentionSelect = (adminName) => {
const currentEditor = trixEditorRef.current.editor
const cursorPosition = currentEditor.getSelectedRange()[0]
const mentionText = `${adminName} `
currentEditor.insertString(mentionText, cursorPosition)
const newCursorPosition = cursorPosition + mentionText.length
currentEditor.setSelectedRange(newCursorPosition, 0)
setMentionSuggestions([])
setShowDropdown(false)
currentEditor.element.focus()
}
// html
<CCol md={12}>
<input id="x" type="hidden" name="content" ref={contentEl} />
<TrixEditor
onChange={handleEditorChange}
placeholder="editor's placeholder"
value={trixData.pageData.html}
input="x"
ref={trixEditorRef}
/>
</CCol>
dropdown menu that shows mentions
{showDropdown && (
<div id="mention-suggestions">
{mentionSuggestions.map((adminName, index) => (
<div
key={index}
className="mention-suggestion"
onClick={() => handleMentionSelect(adminName)}
>
{adminName}
</div>
))}
</div>
)}