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.

1

2 Answers 2

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> 
Sign up to request clarification or add additional context in comments.

1 Comment

to add, the issue is Other string ${<a target="_blank" href={someVariable}>text inside link</a>} is a fragment and jsx has a hard time parsing it
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> 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.