CustardBun
CustardBun

Reputation: 3877

How to insert variable string into link tag using react & typescript?

I'm new to using javascript and typescript and have a link that needs to be generated based on some other variables. I'm now just trying to stick that link into

<a href="Some Link"> Some Text </a>

Both the "Some Text" and "Some Link" values come from variables.

I can successfully get the "Some Text" from a variable

<dd><a href="{thisDoesNotWork}">{someText}</a></dd>

but I can't get the href to work, as it just takes the string in as a literal. How do I get the href to work with a variable string?

As requested, here's a bit more detail:

Current typescript:

return (
   <div>
      ....
      <dd><a href="hardCodedSomething">{someText}</a></dd>
   </div>
)

Want:

var someDynamicUrl = "somepath.com" + someId

return (
   <div>
      ....
      <dd><a href="someDynamicUrl">{someText}</a></dd>
   </div>
)

Upvotes: 2

Views: 4958

Answers (2)

shuhat36
shuhat36

Reputation: 407

If you typed the value as 'String', then try with 'string'. For reference: What is the difference between types String and string?

Upvotes: 0

Gr&#233;gory Bourgin
Gr&#233;gory Bourgin

Reputation: 932

First, your issue is more related to react than typescript.

You're close to make it work:

  • val should be var
  • href attribute value should be defined with curly brackets also

Here is the corrected code:

var someDynamicUrl = "somepath.com" + someId;
var someText = "your text";

return (
   <div>
      ....
      <dd><a href={someDynamicUrl}>{someText}</a></dd>
   </div>
);

Upvotes: 2

Related Questions