Use valid anchorsJS-0739
JavaScript frameworks and libraries like React have made it very easy to add or remove functionality from standard HTML elements. This has led to anchors often being used in applications based on their appearance and function instead of what they represent. While it is possible, for example, to turn the <a>
element into a fully functional <button>
element with ARIA, the native user agent implementations of HTML elements are to be preferred over custom ARIA solutions.
It is recommended to use a valid anchor to avoid confusion while reading a code.
Here are a few scenarios where this issue will be raised:
You need a clickable element
In this scenario, use the onClick
property. onClick
is the standard handler used to detect whether an element has been pressed.
<a onClick={onClickHandler} />
<a href="#" onClick={onClickHandler} />
<button onClick={onClickHandler}>Authenticate</button>
You need to navigate to a different page via a hyperlink
If you need to visit a different page, use the a
tag's href
attribute to control the URL you will navigate to.
<a href="/dashboard">Dashboard</a>
<a href="/jobs">Career</a>
A UI interaction such as a button press must take place
Buttons are usually represented by the dedicated <button>
tag, but can also make use of the <a>
tag, without the href
attribute. Removing this attribute will ensure that the page does not navigate elsewhere when the anchor element is clicked on. It is generally recommended to prefer using <button>
and not <a>
when defining buttons.
<a onMouseEnter={expand}>Table of Content</a>
<button onClick={playHandler}>Play</button>
Bad Practice
// Anchors should be a button
<a onClick={foo} />
<a href="#" onClick={foo} />
<a href={"#"} onClick={foo} />
<a href={`#`} onClick={foo} />
<a href="javascript:void(0)" onClick={foo} />
<a href={"javascript:void(0)"} onClick={foo} />
<a href={`javascript:void(0)`} onClick={foo} />
// Missing href attribute
<a />
<a href={undefined} />
<a href={null} />
// Invalid href attribute
<a href="#" />
<a href={"#"} />
<a href={`#`} />
<a href="javascript:void(0)" />
<a href={"javascript:void(0)"} />
<a href={`javascript:void(0)`} />
Recommended
<a href="https://github.com" />
<a href="#section" />
<a href="foo" />
<a href="/foo/bar" />
<a href={someValidPath} />
<a href="https://github.com" onClick={foo} />
<a href="#section" onClick={foo} />
<a href="foo" onClick={foo} />
<a href="/foo/bar" onClick={foo} />
<a href={someValidPath} onClick={foo} />