No template strings for a href in react?

Hey guys just noticed that I can’t make use of template strings for <a href=``> like this in jsx.

How do you make links dynamic here? it’s going to be an external link.

Have you tried wrapping your template string in curly braces, {}? In JSX land you have to do a sort of ‘escape’ into normal JavaScript. so something like:

linkVariable = '/'
<a href={`https:/${linkVariable}`}>This Is A Dynamic Link</a>

Can also return a url from a function

renderUrl = (user) => {
  if(user.isLoggedIn) {
     return `${user.username}`
     return ``

<a href={this.renderUrl(this.props.user)}>Dynamic link</a>
1 Like

Just to add to what kylec said, if you have a literal string property, then you can use that — <Foo bar="baz" />. But a template string is a function, so it maybe looking at it that way will make it clearer why it won’t work. It needs to be in curly brackets so JSX can evaluate it — <Foo bar=function(x) { return 'Value ' + x + ' in a string'; } /> — that won’t work.

Edit: apropos of nothing, the way template strings work, as functions, means you can abuse them in various ways. Don’t like using brackets?



// etc, as long as the function only takes one string argument

afaik only graphql stuff has really made much use of this, like

this {
  is {
1 Like

Thanks for your feedbacks guys!