Search code examples
javascriptregexreact-nativereplacejsx

React native display [object Object] after returning it


I receive some string that containt html tags. Exemple : "Hello,click <u>here</u>" I create a function for interpret them with the goal to render it under react native :

formating(text){
        // Define regular expressions to match HTML tags
        const boldRegex = /<b>(.*?)<\/b>/g;
        const italicRegex = /<i>(.*?)<\/i>/g;
        const underlineRegex = /<u>(.*?)<\/u>/g;
        const lineBreakRegex = /<br\s?\/?>/g;

        let formattedText = text
          .replace(boldRegex, (_, content) => <Text style={{ fontWeight: 'bold' }}>{content}</Text>)
          .replace(italicRegex, (_, content) => <Text style={{ fontStyle: 'italic' }}>{content}</Text>)
          .replace(underlineRegex, (_, content) => <Text style={{ textDecorationLine: 'underline' }}>{content}</Text>)
          .replace(lineBreakRegex, () => <Text>{'\n'}</Text>);

        return  <Text>{formattedText}</Text>
    }

The problem is that when i display it in my application :

<View>
    {string.formating("my string")}
</View>

It render me "Hello,click [object Object]"

So the in the return is well interpret and the problem come form the replace but impossible to find a solution.

Thank you in advance for your help.


Solution

  • The solution was to use reactStringReplace install with yarn add react-string-replace.

    Here the new code :

    formating(text) {
            const replacements = [
                { regex: /<b>(.*?)<\/b>/g, component: (match, i) => <Text style={{ fontWeight: 'bold' }}>{match}</Text> },
                { regex: /<i>(.*?)<\/i>/g, component: (match, i) => <Text style={{ fontStyle: 'italic' }}>{match}</Text> },
                { regex: /<u>(.*?)<\/u>/g, component: (match, i) => <Text style={{ textDecorationLine: 'underline' }}>{match}</Text> },
                { regex: /<br\s?\/?>/g, component: (match, i) => <Text>{'\n'}</Text> }
            ];
    
            let formattedText = text;
            replacements.forEach(({ regex, component }) => {
                formattedText = reactStringReplace(formattedText, regex, component);
            });
    
            return <Text>{formattedText}</Text>;
        }
    

    Thank you to @Wiktor Stribiżew for gave me this track.