Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert React variable as attribute in HTML tag

Tags:

html

reactjs

I am trying to obtain the following line

<a href="/users/users/authentication" rel='nofollow'>

Note the rel='nofollow'

Within the render method of my React component, I have this JSX syntax:

render() {
  const rel = "rel='nofollow'";
  return (
    <div>
      <a href="/users/users/authentication" {rel}>
    </div>
  );
}

I get a :

Error: /~/Scripts/Navigation.jsx: Unexpected token, expected "..."

I also tried with

let rel = { __html: "<b>Hey</b>" };

and

<a href="/users/users/authentication" dangerouslySetInnerHTML={rel}>

which fails too but anyway dangerouslySetInnerHTML is supposed to inject some stuff between the opening and closing tag not within as an attribute of the tag.

What would be the correct JSX syntax to make that happen?

like image 216
Jerome Avatar asked May 14 '26 16:05

Jerome


1 Answers

You'd first have to decide what "shape" of your rel value should be. Would it be a text? or would it be an object?

1 rel is a text.

If the rel is passed as a raw text, such as nofollow, you'd have to assign the rel property manually.

function LinkWithPropertyAssignment() {
  const rel = "nofollow";

  return (
    <a href="https://www.google.com" rel={rel}>
      Google
    </a>
  );
}

2 rel is an object.

If the rel was passed as an object, such as {rel: 'nofollow'}, then you can simply pass the object to the anchor element.

function LinkWithObjectSpread() {
  const rel = { rel: "nofollow" };

  return (
    <a href="https://www.bing.com" {...rel}>
      Bing
    </a>
  );
}

You can see that both will add rel='nofollow' attribute.

rendered HTML

Demo

You can follow along on CodeSandbox.
Edit so.answer.56133987

like image 172
dance2die Avatar answered May 17 '26 06:05

dance2die



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!