Tomasz Waszczyk
Tomasz Waszczyk

Reputation: 3139

Passing React variable to "href" attribute

I try to pass a value of variable with path to href, I have issue with make it working:

export const TechnicalInformationPure = ( props: AllProps ) => {
  const { t } = useTranslation();
  const { component } = props;

  let hrefLink = '/solution/components/' + component?.id + '/attachments/' + attachment.id;

  console.log(component)

  return (
    <DetailsBox title={t('catalogPage.componentDetails.specs.technicalInfo')}>
      <Typography variant="body1" component="p" gutterBottom>
        {component?.attachments.technical_docs.map(attachment => (
          <li style={{ listStyleType: 'none' }} key={1}>
            <a target="_blank" rel="noopener noreferrer" href={attachment.toString()}>
              {attachment.filename.toString() + attachment.format.toString()}
            </a>
            {<Link target="_blank" href="HerePath">Download</Link>}
          </li>
        ))
        }
      </Typography>
    </DetailsBox>
  );
};

How to assign a hrefLink variable to have it in the line below:

{<Link target="_blank" href="HerePath">Download</Link>}

I am sure that something I think bad, but no idea how to solve it working as I want.

Upvotes: 1

Views: 6451

Answers (2)

Kolade Chris
Kolade Chris

Reputation: 195

You can do it in the exact way you embed variables in vanilla JavaScript. That is, with backticks, dollar sign, and curly braces.

I was working with the YouTube API and wanted to make the videos play when the user clicks the thumbnail. This is how I did it:

 href={`https://www.youtube.com/watch?v=${video.id.videoId}`}

Upvotes: 1

macborowy
macborowy

Reputation: 1534

Try to assign hrefLink like this:

<Link target="_blank" href={hrefLink}>Download</Link>

Full <li> element:

<li style={{ listStyleType: 'none' }} key={1}>
  <a target="_blank" rel="noopener noreferrer" href={attachment.toString()}>
    {attachment.filename.toString() + attachment.format.toString()}
  </a>
  <Link target="_blank" href={hrefLink}>Download</Link>
</li>

Upvotes: 4

Related Questions