thedanotto
thedanotto

Reputation: 7327

Dynamic href tag React in JSX

// This Javascript <a> tag generates correctly
React.createElement('a', {href:"mailto:"+this.props.email}, this.props.email)

However, I'm struggling to recreate it in JSX

<a href="mailto: {this.props.email}">{this.props.email}</a>

// => <a href="mailto: {this.props.email}"></a>

The href tag thinks the {this.props.email} is a string instead of dynamically inputting the value of {this.props.email}. Any ideas on where I went amiss?

Upvotes: 35

Views: 60816

Answers (4)

anil karikatti
anil karikatti

Reputation: 31

I think this may be very easy...try it

<a href={`mailto:${email}?subject=${subject}&body=${text}`}>{email}</a>

Upvotes: 0

Oded BD
Oded BD

Reputation: 3286

A nicer way to do this in my opinion will be to split it into a function and a JSX attr, something like that:

  <Button
    onClick=sendMail
  >
    Send mail
  </Button>
const sendMail = () => {
  const mailto: string =
    "mailto:[email protected]?subject=Test subject&body=Body content";
  window.location.href = mailto;
}

Upvotes: 4

Sean Clancy
Sean Clancy

Reputation: 661

A slightly more ES6 way to do what Patrick is suggesting would be to use a template literal:

<a href={`mailto:${this.props.email}`}>email</a>

Upvotes: 45

Patrick
Patrick

Reputation: 13984

It is returning a string because you are assigning it to a string.

You'll want to set it to a dynamic property, that includes a the string at the beginning of it

<a href={"mailto:" + this.props.email}>email</a>

Upvotes: 64

Related Questions