how can i use react-mentions

219 views Asked by At

i installed react-mentions and I created a special component for it and I am trying to use it in another component, CreatPost component. so that the user can mention other users in his post.

it is assumed that as soon as I type @, the system reviews username suggestions, or when I type a letter after it, it suggests usernames that starts with this letter.

but when i type @ nothing happened

Mention.jsx component:

const Mentions = () => {
    const [value, setValue] = useState("");
    const showToast = useShowToast();
    console.log("Value: ", value);


      const getUsers = async() => {
        try {
          const users = await fetch(`http://localhost:5000/api/users/users`)
          const data = await users.json();
          if(data.error) {
            return;
          }
        } catch (error) {
          showToast("Error", error, "error")
          console.log(error)
        }
      }
      getUsers();


  return (
    <Box>
        <MentionsInput 
        style={defaultStyle}
        value={value}
        onChange={(e) => setValue(e.target.value)}
        allySuggestionsListLabel={"Suggested mentions"}
        >
            <Mention 
            style={defaultMentionStyle} 
            data={getUsers}/>
        </MentionsInput>
    </Box>
  )
}

export default Mentions

textarea in the CreatePost component that I'm trying to make it contains Mention

 <Textarea
   placeholder= "say something..."
   onChange={handleTextChange}
   value={postText}>
   <Mentions />
   </Textarea>
1

There are 1 answers

6
Ashish Chauhan On

I guess you forgot to add a trigger prop in the mention tag.

Try to modify your code like this:

<Box>
      <MentionsInput
        value={value}
        onChange={(e) => setValue(e.target.value)}
        allowSuggestionsAboveCursor
        style={{ input: { padding: 10 } }}
        markup="@[__display__](__type__:__id__)"
      >
        <Mention
          trigger="@"
          data={(search) => {
            const filteredUsers = users.filter(user =>
              user.username.toLowerCase().includes(search.toLowerCase())
            );

            return filteredUsers;
          }}
          renderSuggestion={(suggestion, search, highlightedDisplay, index, focused) => (
            <div className={`user ${focused ? 'focused' : ''}`}>
              {highlightedDisplay}
            </div>
          )}
          onAdd={(id, display) => console.log('Added mention', id, display)}
        />
      </MentionsInput>
    </Box>