Web development: React Comments and @ Mentions

Sem Gebresilassie
2 min readFeb 10, 2022

Recently at work, I attempted to develop a “comments” section. We wanted our users to have the ability to “mention” other users in comments — to understand what they signify — think of the comments and mentions you’ve likely used to tag friends on Twitter, Facebook, or Instagram.

If React is your front-end, you can use a well-known library called react-mentions, to include mentions in comment sections.

Let’s look at how you can add a mention to your comment section in the front-end using react-mentions.

  • Installing react-mentions
npm install react-mentions — save--- or ---yarn add react-mentions
  • import mention components
// import MentionsInput, Mention from react-mentionsimport { MentionsInput, Mention } from ‘react-mentions’// simply use component as followconst users = [{ id: "1", display: "Jimmy" }, { id: "2", display: "Ketut"}, { id: "3", display: "Gede" }]   <MentionsInput 
value={this.state.comment}
onChange={event => setComment({comment: event.target.value})
}>
<Mention
trigger=”@”
data={users}
/>
</MentionsInput>

You can find a working example code I left on sandbox here

The best part is, react-mentions is very configurable compared to other libraries that have the same functionality. You can learn more about the configuration props are listed here

For instance, it has a configuration prop called markup which encapsulates your specified text with a markup that you choose — and when you mention someone — it encapsulates the mentioned user as @[username][userId] together with the actual “text/comment” in the following way.

Hello @[John][123]). How are things doing for you?.

Whereas other libraries os this kind separates the text and mentions, such as (Hi John, how are you doing) and give you a separate array of mentions like [John] — I found this to be an additional work and difficult to store and retrieve from the database.

--

--

Sem Gebresilassie

Media and Software professional sharing life lessons, random ideas and insights. Slow is smooth, smooth is fast.