How conditionally add an HTML attribute to an element in Astro

372 views Asked by At

I am using Astro and TypeScript.

How do I add conditionally an HTML attribute rel="noreferrer" to an element in Astro?

So when targetBlank = false it doesn't render rel attribute in the dom?

Or is the only solution to conditionally show another HTML element?

---
type Props = {
  to: string;
  targetBlank?: boolean;
};

const { to, targetBlank = false } = Astro.props;
---

<a
  href={to}
  target={targetBlank === true ? '_blank' : '_self'}
  rel={targetBlank === true ? 'noreferrer' : ''}
>
  <slot />
</a>
1

There are 1 answers

0
Tachibana Shin On BEST ANSWER

use undefined:

---
type Props = {
  to: string;
  targetBlank?: boolean;
};

const { to, targetBlank = false } = Astro.props;
---

<a
  href={to}
  target={targetBlank === true ? '_blank' : '_self'}
  rel={targetBlank === true ? 'noreferrer' : undefined}
>
  <slot />
</a>