2

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 ?

Jerome
  • 21
  • 1
  • 4
  • 1
    You don't have to to change anything about HTML syntax to set a basic attribute in React, unless it's a multi-word attribute, which in some cases is camelCased. But simply putting `````` should work. – Chris B. May 14 '19 at 15:38
  • I believe this is exactly what you're looking for https://stackoverflow.com/questions/38619182/what-is-the-best-way-to-have-variable-attributes-in-jsx – Henrikh Kantuni May 14 '19 at 15:39

3 Answers3

9

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

dance2die
  • 35,807
  • 39
  • 131
  • 194
0
  render() {
  const theRel = "nofollow";
  return (
    <div>
      <a href="/users/users/authentication" rel={theRel}/>
    </div>
  );
}
Amir-Mousavi
  • 4,273
  • 12
  • 70
  • 123
0

You can set rel like this:

render() {
  const rel = "nofollow";
  return (
    <div>
      <a href="/users/users/authentication" rel={rel}>Hey</a>
    </div>
  );
}
gergana
  • 681
  • 6
  • 11