javascriptreactjsjsxtemplate-literals

How to use template literals (``) within template literals?


I have a very specific edge case which I need to use a template literal within a template literal but can't get it done.

The code looks something like this:

<p>Something something <a href={`${SOMELINK}/blah`}>SomeLink</a></p>

However I will have to wrap that in a function, while maintaining the value of the SOMELINK variable, this causes errors to happen. Whether I escape the ticks or not.

someFunction (`<p>Something something <a href={`${SOMELINK}/blah`}>SomeLink</a></p>`)

With escaped ticks I get the following error message:

Error: Expected SOMELINK but none provided

Without, I get:

Unexpected token, expected ","

How do I handle this?

Edit: It should probably be noted that the code being passed in someFunction will be rendered and it need to be used. It will eventually be passed in to another tag through dangerouslySetInnetHTML. So it will look something like this:

<div dangerouslySetInnerHTML={{__html: someFunction(`<p>Something something <a href={`${SOMELINK}/blah`}>SomeLink</a></p>`)}}/>

Not sure if this is relevant, but someFunction just does some modifications on the text.


Solution

  • I think you're overcomplicating it. If you only need to maintain the value of SOMELINK, this should work:

    someFunction(`<p>Something something <a href="${SOMELINK}/blah">SomeLink</a></p>`)