Green Eagle
Green Eagle

Reputation: 227

react native string replace with image

I am currently working on a app where user can mention their friends. If user inputs something with @user1 I will get user1's image and display on the message.

Lets say if user types Hey @user1, whats up ? then in place of @user1, his thumbnail should be displayed.

User's thumbnail is in its username path somewhere like user1.jpg

function getTextWithThumb(str) { 
        var withThumb =  str.replace(userCheckRegex, `<Image source=require("../" + ${$&} + ".jpg") />`) 
        return withThumb
}

Here I am stucked at returning Image Component along with text dynamically out of react component.

<Text>{getTextWithThumb("Hey @user1, whats up ?")}</Text>

Which should give something like,

<Text> Hey <Image source="some_source" />, whats up ? </Text>

Is there any way I can achieve this ? Really need help here.

Thank you

Upvotes: 1

Views: 2723

Answers (1)

Colin Ricardo
Colin Ricardo

Reputation: 17269

I think you want something like:

function getTextWithThumb(str) { 
  const imageSource = str.replace(userCheckRegex, `require(../${$&}.jpg)`);
  return <Image source=`${imageSource}`/>  
}

Then later:

<Text>{`Hey, ${getTextWithThumb("@user1")}, what's up?`}</Text>

As @Robbie mentioned, you might have to have your <Image /> within a <View> tag.

Upvotes: 1

Related Questions