Eric the Red
Eric the Red

Reputation: 5454

How can I fix jsx-a11y/anchor-is-valid when using the Link component in React?

In a React app

<Link to={`/person/${person.id}`}>Person Link</Link>

results in the following eslint error

The href attribute is required on an anchor. Provide a valid, navigable address as the href value jsx-a11y/anchor-is-valid

The Link component results in a valid href attribute.

<a href="#/person/2">Person Link</a>

What is the point of this error? How do I fix this?

Any help would be greatly appreciated!

Upvotes: 53

Views: 54226

Answers (5)

vedanth bora
vedanth bora

Reputation: 782

adding this in my .eslintrc file in setting > rules fixed the issue

"jsx-a11y/anchor-is-valid": [
      "off",
      {
        "components": ["Link"],
        "specialLink": ["hrefLeft", "hrefRight"],
        "aspects": ["noHref", "invalidHref", "preferButton"]
      }
    ]

Upvotes: -1

sergioviniciuss
sergioviniciuss

Reputation: 4696

As per they suggest in the https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/master/docs/rules/anchor-is-valid.md

you can do the following: call the link component with tag inside of it, as per in nextjs docs. then, you can simply use the passHref prop in the Link component, and add a dummy href attribute in the tag

Something like this:

<Link to={`/person/${person.id}`} passHref> <a href="replace">Person Link</a></Link>

It should do the trick :) The eslint ignore rules suggested above didn't work for me, btw, but this solution did, and it's one of the recommended ones in the docs about the rule.

Upvotes: 3

Roni Chabra
Roni Chabra

Reputation: 1

you can just write some text content inside the "a" tag and hide it with CSS (font-size:0px or something

Upvotes: -15

Tomasz Mularczyk
Tomasz Mularczyk

Reputation: 36179

The Link component generates href attribute so in the end anchor tag is valid from the accessibility point of view. Add an exception to .eslintrc:

{
  "rules": {
    "jsx-a11y/anchor-is-valid": [ "error", {
      "components": [ "Link" ],
      "specialLink": [ "to" ]
    }]
  }
}

Additionally, there is the same issue with a answer on GitHub.

Upvotes: 78

turonno
turonno

Reputation: 171

Perhaps you meant to put backticks instead of single-quotes in order to create a template literal. Try the following:

<Link to={`/person/${this.state.id}/edit`}>Edit</Link>

Upvotes: -15

Related Questions