Home > Net >  React Native : replace a string with a Text component
React Native : replace a string with a Text component

Time:04-13

I am trying to convert some homemade tags/bbcode and for doing so I need in some case not to return a string but a text component, I am trying to do that with this small function but the issue is that when I render it it display [object Object] instead of the component.

helper.js

import { Text } from "react-native";
    const decodeTags = (string) => {
      string = string.replace(
        /\[b\](. )\[\/b\]/isu,
        <Text style={{ fontWeight: "bold" }}>$1</Text>
);

profilBio.js

<Text style={styles.bio}>
  {decodeTags(props.profil.bio)}
</Text>

Render

[object Object] (instead of some text with a part in bold)

CodePudding user response:

If the request is how to update styles conditionally;

To update styles conditionally;

  <Text style={(this.state.myCondition == true) ? styles.bio_font_weight : styles.bio}>{decodeTags(props.profil.bio)}</Text>

And update decodeTags() to return only the data, not a Text component.

CodePudding user response:

You'll need some pre-processor function which would basically split the string at the string which you need to make bold. After that, just basic string substring operation and concatenating the parts.

Ex:

    const highlightKeyword = useCallback((originalString = '', searchQuery) => {
        let s = originalString;
        let searchStartIndex = s.indexOf(searchQuery);
        return (
          <Text>
            <Text style={Styles.text}>{s.substr(0, searchStartIndex)}</Text>
            <Text style={[Styles.text, {color: Colors.RED}]}>{searchQuery}</Text>
            <Text style={Styles.text}>
              {s.substr(searchStartIndex   searchQuery.length, s.length)}
            </Text>
          </Text>
        );
      }, []);


highlightKeyword(props.profil.bio,searchQuery)
  • Related