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?

2
  • 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 <a href="/users/users/authentication" rel='nofollow'> should work. Commented May 14, 2019 at 15:38
  • I believe this is exactly what you're looking for stackoverflow.com/questions/38619182/… Commented May 14, 2019 at 15:39

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

You can set rel like this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.