Insert a component into a string in React Native

21 Views Asked by At

I have a string with special placeholders where the format is %<placeholder_name>%, such as %ICON%, %NEWLINE%, and so on. These texts are rendered inside a Text component. I want to replace the %ICON% placeholder for a <FontAwesomeIcon/> icon.

When there is no need to insert Fontawesome icons inside my text (so they are in the beginning or end), I have no problem, I just put them like <Text> <FontAwesomeIcon icon={faBell} /> {myText} </Text>, and simply delete the placeholder from the text. The problem arises when the myText variable contains the %ICON% placeholder, which should be replaced.
I already tried some workarounds, like:

<Text>{ myText
.split("%ICON%")
.join(<FontAwesomeIcon icon={faBell}/>)
}</Text>

or

<Text>{ myText.replace("%ICON%",<FontAwesomeIcon icon={faBell}/>) }</Text>

but none of them worked, since that component is an object and cannot be converted to string (besides the basic [object Object] conversion). They also - obviously - violates a TypeScript rule, since these functions' expected parameters are strings, and not components.

0

There are 0 best solutions below