Search code examples
javascripthtmlreactjstext-to-html

How can I inject a span into a string and have it printed in my react app as HTML


I have this code, that can take a string and some variables and inject the variables into the string. This is needed in my app because the text often comes from a CMS and have to be editable. Sometimes the variable part of the string is colored or a different font so I was trying to make it so that i could wrap it in if necessary. But my react app posts everything as a string.

 var VariableInjection = (stringToEdit, variablesToInject) => {
    const matches = stringToEdit.match(/{[a-z][A-z]*}/g);
    const strippedMatches = matches.map(m => m.replace('{', '')).map(m => m.replace('}', ''));

    for (let i = 0; i < matches.length; i += 1) {
        const replaceWith = variablesToInject[strippedMatches[i]];
        if (typeof replaceWith === 'string' || typeof replaceWith === 'number') {
            stringToEdit = stringToEdit.replace(matches[i], replaceWith);
        } else {
            stringToEdit = stringToEdit.replace(matches[i], `<span class="${replaceWith.class}">${replaceWith.value}</span>`);
        }
    }

    return stringToEdit;
};

VariableInjection("this is the {varA} and this is the {varB}", { varA: 1, varB: 2}) gives:

'this is the 1 and this is the 2'

VariableInjection("this is the {varA} and this is the {varB}", { varA: 1, varB: { value:2, class:"test Class"}) gives:

'this is the 1 and this is the <span class="test Class">2</span>'

Solution

  • It sounds like you'll need to use dangerouslysetinnerhtml on the component that renders the text. This isn't necessarily the best solution (use with caution), as the name implies, but it should solve the problem with the way your code works.

    Edit: JSFiddle

      render: function() {
        return <div dangerouslySetInnerHTML={{ __html: html }}></div>;
      }