React native user tags inside text input

Viewed 675

I can't seem to properly figure out how to have formatted user tags that are editable inside of a text input.

For example:

const stateString = "{{ userId:1 }} is feeling great.";

To display a formatted user tag, I take that value, run it through a function, and it outputs "John is feeling great.", where John has a visible background color.

My problem is that on the next onChange trigger of my TextInput, e.nativeEvent.text is "John is feeling great." without any of the formatting.

If I feed that back to the TextInput component directly, I will lose the formatting as it will no longer have {{ userId: 1 }}.

My only option is to take stateString and compare it to e.nativeEvent.text, see what changed, and manually re-inject the user tags in.

The problem with that is that it's complicated (the change can be an added character, removed character, or removed multiple characters), and the fact that you can have John is with John coming from {{ userId:1 }} is with {{ userId:2 }}. Two different people, same first name.

The problem is that I need {{ userId:1 }} to send to the server, so it knows which users are mentioned in the comment.

Any ideas would be appreciated!

1 Answers

You'll have to keep track of both the encoded string and the formatted string.

Or the formatted string and the map of encodings. I've done both in the past but basically the strategy is:

tokens: [{type:mention, userId:1, position: 0, endPosition:4}]
// or
rich: "{{ user:1 }} is so hawt"
// or
rich: "yourProtocol://yourDomain/user?id=1&username=John is so hawt"

slug: "John is so hawt"

Now slug can be derived from rich. It's hard to maintain both in real time as a user types though. You have to account for:

  1. Deleting into the mention.
  2. Editing text in a mention.
  3. Deleting many characters, including a partial mention.
  4. Deleting many mentions.
  5. Probably more...
Related