Search code examples
javascriptreactjsecmascript-6string-literals

passing js string literal with html into component and retain html


I have an array of objects, where each object gets passed into a child component. One of the values of the object is a text blob as a string literal. This blob contains HTML links. I would like to preserve this links in the child component. Here is what it looks like...

`This is my text literal with a ${<a href="http://link.com">Link</a>}.`

I also tried creating a react object on the fly like this:

`This is my text literal with a ${React.createElement('a', { href: 'https://link.com' }, 'Link')}.`

This both rendered like this:

This is my text literal with a [object Object].

How do I get this to display the link?


Solution

  • An untagged template literal (it's not a string literal) is evaluated immediately and results in a string. Within your template, you're creating a link element and embedding it in that string, so the toString method is called. You're seeing the result of the default toString, [object Object].

    You can't pass a template into a component. You could pass in a fragment containing the link:

    <>This is my text literal with a <a href="http://link.com">Link</a>.</>
    

    That's React v16.2+ syntax. If you're using something older, you may have to use React.Fragment directly (v16+).

    If you're using something before v16, you won't have fragments; the usual solution then is a span or div (span in this case I'd say):

    // v15 and earlier
    <span>This is my text literal with a <a href="http://link.com">Link</a>.</span>