0

I'm trying to concatenate a string and HTML inside a JSX expression, but I can't seem to do it correctly. The code in my render function looks like this:

<span>
   {'preferred string' || `Other string ${<a target="_blank" href={someVariable}>text inside link</a>}`}
</span>

What I want it to render is: "Other string text inside link"

What it actually renders is "Other string [object Object]"

I've tried a few different strategies but am having no luck. Any advice is greatly appreciated.

  • take a look at this: https://stackoverflow.com/questions/39523040/concatenating-variables-and-strings-in-react/39523078 – Zombie Jun 14 '18 at 20:04

2 Answers2

2

You want something along the lines of:

<span>
  {'preferred string' || <p>Other string <a target="_blank" href={variable}>text inside</a></p>}
</span>

The key thing is the paragraph tags are added. In your code, React is struggling to interpret multiple different languages at the same time.

Keep in mind that this solution will, similar to the code that you gave, only show the second result if the 'preferred string' is empty or null, and as is, it is hard-coded to have some value, so the second half of the or statement will never show.

Edit: if your strings are in fact variables, then you'll need to exit again for 'other string' like so:

<span>
  { stringVariable || <p>{otherStringVariable}<a target="_blank" href={variable}>{insideTextVariable}</a></p> }
</span>
Blake Steel
  • 378
  • 1
  • 12
0

If you want only to concatenate the string with a tag, you can try this simple way:

<>
    preferred string || Other string <a target="_blank" href={someVariable}>text inside link</a>
</>

or, something like this:

<span>
       {'preferred string' || <span>Other string <a target="_blank" href={someVariable}>text inside link</a></span>}
</span>
Alison Borba
  • 131
  • 1
  • 2