Include jsx components in strings file

Viewed 143

In React and React Native, how can I include jsx components into my strings.js file?

I have created a strings.js file to store all of the copy-text my app uses. This works fine for regular text. However, if the text itself contains other React components, it becomes a problem.

Example:

const strings = {
    welcomeScreen: {
        screenTitle: 'Welcome',
        heading: '<TextBold>Thank you</TextBold> for installing our app!',
        paragraph: 'Lorem, ipsum dolor sit<LineBreakSmall/>consectetur adipisicing.',
    },
};

export default strings;

screenTitle works, heading and paragraph do not work. What do I need to change?

PS: I am aware of the JS array notation, but am wondering if there is another way? In particular, with that notation, I would need to import e.g. TextBold and LineBreakSmall in my strings.js file.

2 Answers

You could try react-jsx-parser.

React-html-parser or dangerouslySetInnerHTML would only work for standard html tags, not JSX.

If you want to show heading and parameter string as html on your web page, then you can you reacct-html-parser npm library, it will convert your string as html.

Example :

import React from 'react';
import ReactHtmlParser from 'react-html-parser';

class HtmlComponent extends React.Component {
    render() {
        return (
            <>
                <div>
                    {ReactHtmlParser(string.welcomeScreen.heading)}
                </div>
                <div>
                    {ReactHtmlParser(string.welcomeScreen.paragraph)}
                </div>
            </>
        )
    }
}
Related