DEV Community

Kesaven
Kesaven

Posted on

How to implement user mentions in React chat app without react-mentions and drafts-js library?

I've implemented a user tag functionality while pressing @ and it's working fine.But i couldn't able to highlight the tagged user because i'm using input field..While using libraries like react-mentions and draft-js , I couldnt integrate them into the codebase because of some weird issues..Any idea of implementing the highlighting part in this code would be really helpful..Thanks..https://codesandbox.io/s/charming-pike-bzhzn?file=/src/AutoCompletedText.js

Top comments (1)

Collapse
 
hangindev profile image
Jason Leung 🧗‍♂️👨‍💻 • Edited

I was about to tell you how troublesome it could be and don't do that but I figured that would not be an answer you are hoping for. I am not sure how react-mentions is causing weird issues (if you share the issues we may be able to help) but if your want to build something simple which you can have full control, I took a look at the DOM elements in the react-mentions demo page and recreated a minimal working example. (obviously not production ready)

Edit clever-knuth-m25if

So the basic idea is to save the value state as an array of objects with different types (normal text/mention) instead of plain string. Then you would track the mention texts and place a styled element (e.g. a div with yellow background) behind them. But it can be a headache to sync the positions when handling long text (text longer than the input element or textarea). Learn why in the first few minutes of this talk:

So my suggestion is: try to debug the problem react-mentions is causing you. If not, consider if that is a necessary feature or an @ sign is enough like DEV does.

Apps like Facebook, Twitter don't use input or textarea to style highlight, instead, they use contenteditable div. So if you foresee that your app will need a rich text editor in the future, you can have a look at quilljs and slate. These libraries, including draftjs, all use contenteditable div instead of the native input element which can give you a more customizable input field. AFAIK, quilljs has the best mobile support.