Hi Trailblazers! If you need to implement a social media-like @mention or #hashtag feature with a textbox input inside LWC, then you've come to the right place.
Requirement
- We need a textarea input where users can tag other users using the @ symbol or a hashtag.
- When the user types @, a pop-up should show a list of active users.
- Once selected, the user's handle/username should be inserted into the text area.
Technically not just a user object, but we can use this for any Salesforce
object.
We'll be using the open-source JavaScript library Quill to build this experience in Lightning web components.
Solution
Here are the steps on how to implement this in your Salesforce org:
-
Download the Quill Library from here: Version 1.3.7, Please download this specific file -
quill.tar.gz
. Refer to the image below. -
Upload the zip file into a static resource named
Quill
and make it public. The static resource name should be exactly the same asQuill
. -
Download the code for the
mention
component from here: https://github.com/rahulgawale/Quill-Mention/tree/dev/unpackaged/force-app/main/default/lwc/mention - Deploy the
mention
component to your org. - Refer to the following example to implement the @mention with the above component.
- Here is the Apex code you can use to query the active users' list:
-
Put the below HTML code into your component.
<c-mention class="textAreaBody" at-values={atMentions} hash-values={hashMentions} content-editable onedit={handleEdit} text={text} ></c-mention>
- Set
content-editable
property tofalse
if you want to make itread-only
. -
Set the
at-values
and optionallyhash-values
to thec-mention
component like below, You can load these values from Apex, but for the sake of this demo, I will put hard-coded sample values.
/// at-values [ { Id: 1, Name: "User 1" }, { Id: 2, Name: "User 2" } ] /// hash values [ { Id: 1, Name: "hashtag1" }, { Id: 2, Name: "hashtag12" } ]
-
Use the
handleEdit
function (onedit
event) to handle the changes and capture the text value from themention
component. -
Use the
text
attribute to set the default value to themention
text area input. -
Optionally you can disable the input by setting
content-editable
tofalse
.
No comments :
Post a Comment
Hi there, comments on this site are moderated, you might need to wait until your comment is published. Spam and promotions will be deleted. Sorry for the inconvenience but we have moderated the comments for the safety of this website users. If you have any concern, or if you are not able to comment for some reason, email us at rahul@forcetrails.com