简体   繁体   中英

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!

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 .

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.

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"]
      }
    ]

你可以在“a”标签内写一些文本内容并用CSS(字体大小:0px或其他东西)隐藏它

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM