Web development: React Comments and @ Mentions

Sem G.
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.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Sem G.
Sem G.

Written by Sem G.

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

No responses yet

Write a response