Get Started
- CodeAnt AI
- Control Center
- Pull Request Review
- IDE
- Compliance
- Anti-Patterns
- Code Governance
- Infrastructure Security Database
- Application Security Database
Jsx
Enforce emojis are wrapped in <span>
and provide screenreader access.
function EmojiComponent() {
return (
<p></p>
);
}
-
Ensures emojis are accessible to screen reader users by enforcing that emojis are contained within a
<span>
element with appropriatearia
attributes, making web content more inclusive for visually impaired users. -
Promotes the use of the
role="img"
attribute alongsidearia-label
oraria-labelledby
for emojis, which provides semantic meaning and a textual alternative, crucial for understanding the content’s context in screen reader scenarios. -
Prevents the incorrect assumption that emojis are universally understood or visually accessible, recognizing the need for explicit descriptive text for emojis to convey the intended message or emotion in a text alternative form.
-
Encourages best practices for accessible web development specifically tailored for emoji usage in JSX, ensuring that decorative emojis are marked as such (not requiring screen reader access) while informative emojis are made accessible.
Enforce all elements that require alternative text have meaningful information to relay back to end user.
const UserProfile = () => {
return (
<div>
<img src="user_profile.jpg" />
</div>
);
};
-
This rule ensures that images and other media elements in JSX, such as
<img>
,<object>
,<area>
,<input type="image">
, and custom components simulating these behaviors, have alternative text, enhancing web accessibility for users relying on screen readers to understand the content. Non-text content must have text alternatives that present the equivalent information to ensure that it can be accessed by people with various disabilities. -
It helps in identifying missing alt attributes on media elements which is crucial for SEO as search engines use the alt attributes to understand and index an image’s content. Without alt text, the chances of images being found in search results diminish.
-
The rule promotes best practices in web development by enforcing the inclusion of meaningful alternative text rather than allowing empty or generic descriptions that do not serve a purpose, thereby improving the user experience for those utilizing assistive technologies.
-
By customizing the elements and their custom components to be validated through options, it offers flexibility and ensures the rule’s relevance across different projects with varying requirements, making it a versatile tool in maintaining accessibility standards.
Enforce <a>
text to not exactly match “click here”, “here”, “link”, or “a link”.
// Bad: The anchor text is "click here", which is too vague for users, especially for those using screen readers.
const BadLinkExample = () => {
return (
<div>
For more information, <a href="https://example.com">click here</a>.
</div>
);
};
-
Improves accessibility: By enforcing specific, context-rich text for
<a>
elements rather than generic phrases like “click here,” the rule helps ensure that users, especially those using screen readers, have a clearer understanding of the link’s destination. This makes navigation and comprehension of web content more accessible. -
Enhances user experience: Links with descriptive text provide a better user experience by supplying more information on what to expect before clicking. This clarity can reduce user frustration and increase engagement with the website content.
-
Increases SEO performance: Search engines use link text to understand the content of the linked page, so descriptive links contribute to better SEO. Ambiguous link text, on the other hand, might be missed or undervalued by search engines, potentially harming the site’s search ranking.
-
Encourages best coding practices: The rule promotes attention to detail and thoughtful web design by requiring developers to consider the purpose and destination of each link. This mindfulness can carry over into other aspects of coding and design, leading to higher overall quality in web development projects.
Enforce all anchors to contain accessible content.
// This anchor element has no accessible content, making it a bad practice
// under the 'jsx-a11y/anchor-has-content' rule.
const BadAnchor = () => (
<a href="https://example.com"></a>
);
- This rule specifically targets ensuring that all anchor (
<a>
) elements in JSX have accessible content, which is critical for users who rely on screen readers to navigate content on the web. Without accessible content, these users may encounter anchor elements that provide no context or indication of their function or destination. - The rule allows for flexibility in defining what constitutes accessible content by considering not only direct text content within the anchor but also the presence of certain attributes (
title
,aria-label
) that can describe the purpose or destination of the link to assistive technologies. This caters to a variety of use cases, including those where visual design constraints might discourage visible text. - By including options to extend the rule to cover custom anchor components beyond just the basic
<a>
tag, the rule acknowledges and adapts to the common practice in modern web development frameworks and libraries (like React) of creating reusable component libraries. This ensures that accessibility considerations are extended to these custom components as well. - The rule enforces proactive accessibility practices during the development process itself, aiming to catch and correct instances where anchors may lack accessible content before the code is even deployed. This early intervention helps in building a more accessible web, reducing the need for potentially costly and time-consuming remediation efforts later in the development lifecycle or after deployment.
Enforce all anchors are valid, navigable elements.
// Incorrect usage of <a> without href but with an onClick handler
import React from 'react';
const MyComponent = () => {
const handleClick = e => {
e.preventDefault();
console.log('Anchor clicked!');
};
return <a onClick={handleClick}>Click me</a>;
};
-
This rule specifically addresses the distinction between hyperlinks and buttons, encouraging correct semantic HTML by guiding developers to use links (
<a>
tags) only for navigation purposes and buttons for clickable actions. This distinction is crucial for accessibility as it helps screen readers and other assistive technologies interpret the purpose of elements correctly. -
It includes validation against common pitfalls, such as using anchors without a valid
href
attribute or improperly using JavaScript URLs. These practices can undermine the navigability and security of a web application, leading to a poor user experience, especially for those relying on assistive technologies. -
By recognizing the usage of the JSX spread operator and ensuring that it does not falsely report errors when props are correctly spread across an anchor element, the rule demonstrates consideration for React’s component-based architecture, ensuring that developers do not have to compromise on code reusability and readability to adhere to accessibility standards.
-
The rule’s configurable aspects (
noHref
,preferButton
,invalidHref
) allow teams to tailor the rule to their specific project needs, making it a versatile tool for maintaining both code quality and accessibility standards. This flexibility ensures that the rule can adapt to various coding styles and project requirements without enforcing overly strict guidelines that might not fit every scenario.
Enforce elements with aria-activedescendant are tabbable.
function MyComponent() {
return (
<div aria-activedescendant="someId">
{/* Content here */}
</div>
);
}
-
Ensures that elements with the
aria-activedescendant
attribute are also interactive or focusable by requiring atabIndex
. This is crucial becausearia-activedescendant
is used to manage focus among child elements when the container receives focus. WithouttabIndex
, keyboard users might not be able to interact with these elements as intended. -
Improves accessibility by making elements with
aria-activedescendant
accessible to keyboard navigation. This rule enforces that such elements must be tabbable (by setting a validtabIndex
), which is essential for users who rely on keyboard navigation to access content on the web. -
Helps in aligning with WCAG (Web Content Accessibility Guidelines) and ARIA (Accessible Rich Internet Applications) best practices by enforcing correct use of ARIA attributes together with focusable elements. This alignment is important for creating web content that is accessible to people with disabilities.
-
Aids in avoiding common mistakes in accessibility implementation by automatically catching elements that have
aria-activedescendant
but lack atabIndex
. This preemptive checking saves developers time and ensures a smoother, more accessible user experience without needing extensive manual review or user feedback to identify these issues.
Enforce all aria-*
props are valid.
function MyComponent() {
return (
<div aria-lable="Close">X</div> // Typo in `aria-label`
);
}
- This rule ensures that all ARIA (Accessible Rich Internet Applications) attributes used in JSX code are valid, which helps in maintaining the accessibility standards for web applications. Ensuring that
aria-*
props are valid aids screen readers and assistive technologies in interpreting the web content correctly. - By checking for the correct usage of ARIA properties, it prevents common typos (such as “aria-lable” instead of “aria-label”) and other mistakes that could lead to confusion or inaccessibility for users with disabilities. This not only improves user experience but also aligns with web accessibility guidelines.
- The rule operates by filtering attributes to those starting with “aria-” and then validates their correctness against a known list of ARIA attributes. This automation saves developers time and reduces human error, making it easier to adhere to accessibility standards without requiring deep ARIA expertise.
- By reporting specific errors directly in the development process, it educates developers on proper ARIA usage, potentially increasing the quality of accessible web development practices within a team or among individual developers. This continuous feedback loop helps in gradually improving the accessibility of web projects over time.
Enforce ARIA state and property values are valid.
import React from 'react';
const MyCheckboxComponent = () => (
<div>
<input type="checkbox" aria-checked={true} /> {/* Incorrect, as aria-checked expects a string */}
</div>
);
- This rule ensures that ARIA (Accessible Rich Internet Applications) state and property values adhere to standardized, valid formats, which is critical for screen readers and assistive technologies to interpret and interact with web content accurately, thereby supporting web accessibility.
- By enforcing the use of correct data types for ARIA properties (e.g., string values for
aria-checked
instead of Boolean), this rule aids developers in adhering to ARIA specifications and best practices, reducing the likelihood of accessibility issues caused by incorrect attribute values. - The rule helps maintain a consistent coding practice related to ARIA attributes across a project by automatically flagging incorrect usage, which can be particularly beneficial in larger projects or teams where multiple developers might work on the same codebase.
- It serves as an educational tool for developers, especially those new to web accessibility concepts, by providing immediate feedback on ARIA attribute misuse, which can facilitate a learning curve and encourage more accessible coding habits over time.
Enforce that elements with ARIA roles must use a valid, non-abstract ARIA role.
import React from 'react';
const MyComponent = () => (
// "widget" is an abstract ARIA role and not meant to be used directly.
<div role="widget">I am a custom widget component</div>
);
-
This rule ensures that ARIA roles are valid and not abstract, which directly contributes to making web content more accessible to users with disabilities. Specifically, by enforcing the use of valid, non-abstract ARIA roles, it helps screen readers and other assistive technologies provide meaningful interaction cues to users.
-
The rule includes an option (
ignoreNonDOM
) to skip validation for non-DOM elements. This flexibility allows developers to focus on validating roles in contexts where it matters most, such as in actual rendered HTML, while avoiding unnecessary checks in situations where an element might not directly correlate to a DOM element, thus optimizing development efficiency without compromising on accessibility. -
It allows for customization through
allowedInvalidRoles
, where developers can specify exceptions. This makes the rule adaptable to unique project requirements or when integrating with libraries or frameworks that might use roles in non-standard ways but are still accessible. This adaptability ensures that teams can enforce accessibility standards while also accommodating valid exceptions specific to their project’s context. -
The rule performs checks only if the attribute’s name is
role
and its value isn’tundefined
ornull
. This precision prevents false positives and ensures that developers are alerted only in cases where an invalid ARIA role could genuinely affect accessibility. It focuses on actual issues rather than potential syntactic anomalies, thereby streamlining the debugging process and ensuring that efforts are concentrated on making meaningful improvements to accessibility.
Enforce that elements that do not support ARIA roles, states, and properties do not have those attributes.
function BadComponent() {
return (
<meta name="viewport" content="width=device-width, initial-scale=1" role="presentation" />
);
}
-
This rule helps ensure accessibility by preventing the use of ARIA roles, states, and properties on HTML elements that do not support them, reducing confusion for users of assistive technologies. For instance, adding
role="presentation"
to a<meta>
tag, which does not support ARIA roles, can mislead screen readers and other assistive devices. -
It promotes best practices in web development by enforcing a cleaner separation of concerns, where ARIA attributes are used only where they are intended and supported, enhancing the overall quality of code and making it easier to maintain and debug.
-
By reporting the use of ARIA attributes on unsupported elements, it aids developers in catching potential accessibility issues early in the development process. This proactive approach can save time and resources that might otherwise be spent on revising code to address accessibility concerns identified at later stages.
-
The rule specifically targets a common misunderstanding among developers about how ARIA roles, states, and properties should be applied to HTML content. By providing clear feedback when such attributes are misapplied, it serves an educational purpose, increasing awareness and understanding of ARIA guidelines within the developer community.
Enforce that autocomplete attributes are used correctly.
import React from 'react';
const LoginForm = () => {
return (
<form>
<input type="text" autocomplete="usernamee" name="username" />
<input type="password" autocomplete="new-pass" name="password" />
</form>
);
};
-
This ESLint rule ensures proper use of the
autocomplete
attribute in JSX components, which directly contributes to improving the user experience by allowing browsers to predict the user’s input, thereby speeding up the form-filling process. -
By enforcing correct
autocomplete
values, the rule aids in enhancing form accessibility, making it easier for people with disabilities to fill out forms. Autocomplete hints assist in reducing the amount of typing required, which is particularly beneficial for users with motor disabilities. -
The rule helps in maintaining security best practices by ensuring that fields expecting sensitive information, like passwords, are correctly marked. This prevents browsers from inappropriately storing and autofilling sensitive details, thereby safeguarding user data.
-
It fosters a standardized way of defining form inputs across the project or organization. By stipulating correct
autocomplete
attributes, the rule ensures that developers follow a consistent pattern, reducing bugs related to incorrect form behavior and improving code maintainability.
Enforce a clickable non-interactive element has at least one keyboard event listener.
function MyComponent() {
return (
<div onClick={() => console.log('Clicked!')} style={{ width: 100, height: 100, backgroundColor: 'blue' }}>
Click me!
</div>
);
}
- This rule helps in making web applications more accessible to users with disabilities by ensuring that non-interactive elements (like divs) that have click event listeners also respond to keyboard events. This is crucial for users who rely on keyboard navigation instead of a mouse.
- It enforces good accessibility (a11y) practices by requiring that any element that can be clicked can also be activated using keys such as Enter or Space. This aligns with web accessibility guidelines which advocate for keyboard navigability for all interactive elements.
- The rule prevents developers from inadvertently creating UI components that are inaccessible to people who use assistive technologies. By ensuring elements have the appropriate keyboard event listeners, the rule aids in the compliance with the Web Content Accessibility Guidelines (WCAG) and legal requirements such as the Americans with Disabilities Act (ADA).
- It promotes the development of more inclusive web environments by encouraging the consideration of diverse user interactions beyond traditional mouse-based events. This inclusivity enhances the user experience for a wider audience, thereby potentially increasing the audience and usage of the web application.
Enforce that a control (an interactive element) has a text label.
import React from 'react';
const InaccessibleButton = () => (
<div>
<button><i className="fa fa-save"></i></button>
</div>
);
- Ensures web applications are accessible to users with disabilities by requiring interactive elements to have text labels. This is crucial for screen readers to provide the necessary context for these elements.
- Increases usability for visually impaired users by enforcing labels on controls, allowing them to navigate and interact with web content more effectively.
- Helps maintain consistency in the development process by setting a clear standard for how interactive elements should be implemented, which can lead to more maintainable code.
- Improves SEO as labeled interactive elements contribute to better web standards compliance, making the content more discoverable and indexable by search engines.
Enforce heading (h1
, h2
, etc) elements contain accessible content.
import React from 'react';
const EmptyHeading = () => {
return (
<div>
<h1></h1>
</div>
);
};
export default EmptyHeading;
-
The rule specifically targets ensuring that headings (such as
h1
,h2
, etc.) in JSX elements contain accessible content, which is critical for users who rely on screen readers to navigate web content. By enforcing this rule, developers are prompted to include meaningful text within headings, improving the site’s accessibility. -
It includes flexibility for checking custom component types that act as headings, not just standard HTML heading elements. This is particularly useful in React applications where custom components are used extensively. By including an option for custom components, the rule can be adapted to various development practices, ensuring accessibility considerations are not overlooked in non-standard implementations.
-
The rule proactively prevents the common accessibility issue of empty headings, which can cause confusion for users navigating with screen readers. Empty headings can lead to an inconsistent and frustrating experience, as users might expect content that does not exist. This rule directly addresses and eliminates this potential barrier.
-
By leveraging the
context.report
method when a violation is detected, it provides direct feedback to developers about where and why a violation occurs. This immediate feedback loop helps in educating developers about accessibility best practices and encourages the correction of issues at the source. The rule not only identifies the problem but guides towards a solution, thereby fostering an environment of continuous improvement and learning regarding accessibility.
Enforce <html>
element has lang
prop.
function Page() {
return (
<html>
<head>
<title>My Page</title>
</head>
<body>
<p>Welcome to my page!</p>
</body>
</html>
);
}
- Ensures web accessibility by prompting developers to include the
lang
attribute in<html>
elements, which is crucial for screen readers to provide accurate language support, enhancing the experience for users who rely on assistive technologies. - Helps in search engine optimization (SEO) as specifying the language of a webpage allows search engines to categorize content more effectively, potentially improving the page’s visibility and ranking in search results for users in different language regions.
- Promotes adherence to web standards and best practices as defined by the World Wide Web Consortium (W3C), specifically in meeting the Web Content Accessibility Guidelines (WCAG) which mandate that the primary language of a web page be programmatically determinable.
- Improves content localization and internationalization strategies by enforcing the declaration of a webpage’s language, making it easier for developers and content creators to manage and deliver multi-language content effectively and accurately to a global audience.
Enforce iframe elements have a title attribute.
import React from 'react';
const VideoPlayer = () => (
<iframe src="video12345.mp4" height="200" width="300"></iframe>
);
- This rule specifically ensures that iframes in JSX (React) code include a title attribute, which is crucial for accessibility reasons. Screen readers use the title to provide context to users with visual impairments, making web content more accessible.
- The enforcement of the title attribute in iframes helps in improving the SEO of the webpage. Search engines may use the title attribute to understand the content of the iframe better, thereby aiding in content indexing and improving the page’s search ranking.
- By requiring a title attribute, this rule indirectly encourages developers to be more mindful of the content they embed using iframes. This can lead to better content strategy decisions, such as providing more descriptive titles and improving the overall user experience.
- The rule promotes best practices in code quality and standards. By adhering to accessibility guidelines, developers ensure their applications are compliant with legal standards like the WCAG (Web Content Accessibility Guidelines) and Section 508 of the Rehabilitation Act in the United States, avoiding potential legal issues.
Enforce <img>
alt prop does not contain the word “image”, “picture”, or “photo”.
import React from 'react';
const UserProfile = () => {
return (
<div>
<img src="user-profile-picture.jpg" alt="User profile image" />
</div>
);
};
- This rule helps in enhancing web accessibility by ensuring alternative (alt) text for images is meaningful and not redundant. Alt texts should describe the purpose or content of the image rather than stating it is an image, which screen readers already announce.
- It encourages developers to write more descriptive and context-relevant alt texts. By avoiding words like “image”, “picture”, or “photo”, developers must think about how best to describe the image in a way that would be helpful for users relying on screen readers.
- This rule directly impacts users who rely on assistive technologies for navigating web content. When alt text includes unnecessary words like “image”, it can lead to a frustrating experience for these users, as it does not provide any valuable information about the image itself.
- By enforcing the removal of common redundant words in alt text, this rule can indirectly contribute to better SEO practices. More descriptive and precise alt texts can improve a website’s search engine rankings by providing clearer context and relevance to the content, making it more discoverable.
Enforce that elements with interactive handlers like onClick
must be focusable.
// Bad code example
function MyComponent() {
return (
<div onClick={() => console.log('Clicked!')}>
Click me!
</div>
);
}
- This rule ensures accessibility for users navigating with keyboards by mandating that elements with interactive event handlers, such as
onClick
, must also be focusable. This is crucial because it allows users who rely on keyboard navigation to interact with all interactive elements. - The rule enforces good accessibility practices by requiring elements that act as buttons or other interactive components (but are not inherently focusable, such as
divs
used as buttons) to be explicitly made focusable through attributes liketabIndex
. This directly benefits users who use assistive technologies. - It promotes the semantic use of HTML by pushing developers to consider the roles of elements. For instance, a
div
with anonClick
handler should have an appropriate role (e.g.,role="button"
) if it is acting as a button. This semantic clarity helps assistive technologies interpret and interact with web content effectively. - By highlighting elements that are interactive but not appropriately focusable, the rule aids in identifying potential accessibility issues early in the development process. This preemptive approach can ensure that accessibility considerations are addressed, reducing the need for extensive revisions later on due to accessibility oversights.
Enforce that a label
tag has a text label and an associated control.
// Violates `jsx-a11y/label-has-associated-control`
function UsernameField() {
return (
<div>
<label>Username</label> {/* This is an accessibility issue */}
<input type="text" id="username" />
</div>
);
}
- This rule ensures that labels in JSX markup are explicitly associated with a control element (like
input
,textarea
, etc.), either by nesting the control within the label or using thehtmlFor
attribute. This practice improves form accessibility for users relying on assistive technologies to navigate and interact with your website or application. - It provides options to define custom label and control components beyond the standard HTML elements. This flexibility is essential in complex applications that use custom components for inputs, ensuring that accessibility checks are not limited to native HTML elements.
- The rule allows configuration for the assertion type (
htmlFor
,nesting
,both
, oreither
), giving developers control over how strict their accessibility checks are. This can be adjusted to match project-specific accessibility standards or to progressively improve accessibility in large codebases. - The rule includes a mechanism to prevent infinite recursion by limiting the depth of the search for control components within labels. This thoughtful design prevents potential performance issues in projects with deeply nested components, ensuring that the accessibility linting does not negatively impact development experience.
Enforce that <label>
elements have the htmlFor
prop.
import React from 'react';
const BadForm = () => (
<div>
<label>Email:</label>
<input type="email" id="email" />
</div>
);
- This rule ensures accessibility by enforcing that
<label>
elements are properly associated with their corresponding input elements through thehtmlFor
prop. This association is crucial for screen reader users to understand the form structure and interact with it effectively. - It promotes best practices in web development by ensuring that labels are explicitly linked to their controls, which can also benefit users who rely on voice control software to navigate and interact with web content.
- The rule provides flexibility by allowing developers to configure it according to their needs, such as by specifying custom component types to validate or enabling the allowance of child elements as a form of labeling. This makes the rule adaptable to various coding conventions and accessibility requirements.
- By automatically identifying and reporting instances where the
htmlFor
prop is missing or improperly used, this rule helps to streamline the development process, reduce human error, and ensure that accessibility considerations are systematically integrated into the codebase from the very beginning.
Enforce lang attribute has a valid value.
import React from 'react';
// Example of a component with a missing 'lang' attribute
function MissingLang() {
return (
<html>
<head>
<title>Page without lang attribute</title>
</head>
<body>
Content
</body>
</html>
);
}
// Example of a component with an incorrect 'lang' attribute
function IncorrectLang() {
return (
<html lang="incorrect-value">
<head>
<title>Page with incorrect lang attribute</title>
</head>
<body>
Content
</body>
</html>
);
}
-
Ensures Web Accessibility: The rule is designed to promote accessibility by enforcing the presence of a valid
lang
attribute in JSX elements. This is crucial because the language attribute helps assistive technologies like screen readers pronounce text correctly, improving the experience for users with disabilities. -
Promotes Internationalization: By enforcing a valid
lang
attribute, this rule indirectly supports internationalization efforts. A correctly specified language tag enables browsers and search engines to properly classify and process the content, thereby improving global user reach and engagement. -
Improves SEO: Search engines use the
lang
attribute to offer language-specific search results. Pages with accurately definedlang
attributes are better indexed, which can lead to improved search engine visibility and rankings for content in the specified language. -
Enhances Code Quality: By requiring a valid
lang
attribute, the rule encourages developers to pay attention to important but often overlooked aspects of HTML element attributes. This focus on detail leads to overall better code quality and adherence to best practices in web development.
Enforces that <audio>
and <video>
elements must have a <track>
for captions.
import React from 'react';
function VideoPlayer() {
return (
<video controls>
<source src="movie.mp4" type="video/mp4" />
{/* Missing track for captions */}
</video>
);
}
- The rule directly promotes accessibility by ensuring that
<audio>
and<video>
elements include captions for the deaf or hard of hearing, enhancing web inclusivity and complying with various accessibility standards and laws. - It automatically identifies and signals instances where
<audio>
or<video>
elements are missing<track>
tags designated for captions, thus helping developers catch and resolve potential accessibility issues early in the development process. - By requiring captions via
<track>
elements, this rule indirectly encourages content creators to provide translations, fostering an environment where content is accessible to non-native speakers or to audiences with different language preferences. - Facilitates compliance with WCAG (Web Content Accessibility Guidelines), which is essential for websites that aim to be accessible to as many users as possible and is often a legal requirement for government and educational institution websites.
Enforce that onMouseOver
/onMouseOut
are accompanied by onFocus
/onBlur
for keyboard-only users.
function InteractiveComponent() {
return (
<div
onMouseOver={() => console.log('Mouse over')}
onMouseOut={() => console.log('Mouse out')}>
Hover or focus on me!
</div>
);
}
- Ensures web applications are accessible to keyboard-only users by requiring that mouse events like
onMouseOver
andonMouseOut
have corresponding keyboard eventsonFocus
andonBlur
. This makes sure elements interactive with a mouse are also accessible through the keyboard. - Helps in meeting Web Content Accessibility Guidelines (WCAG) by improving navigation for users who rely on assistive technologies, hence making the application more inclusive.
- Prevents developers from inadvertently creating user interface components that are not accessible to people with disabilities, thus reducing the risk of accessibility-related legal issues.
- Improves user experience for a wider range of users, including those who cannot use a mouse due to physical impairments, by ensuring consistency in how interactive elements respond to user input, regardless of the input method.
Enforce that the accessKey
prop is not used on any element to avoid complications with keyboard commands used by a screenreader.
import React from 'react';
function AccessKeyExample() {
return (
<div>
{/* This input element uses accessKey, which is against our rule */}
<input accessKey="H" placeholder="Press Alt+H for focus" />
</div>
);
}
export default AccessKeyExample;
-
Prevents using the
accessKey
attribute which can interfere with screen reader shortcuts, ensuring that users relying on assistive technologies have a consistent and accessible experience when navigating web applications. -
Encourages developers to find alternative, more universally accessible means to achieve the same functionality, such as ensuring tab navigability or using ARIA roles, thus promoting best practices in web accessibility.
-
Helps in maintaining a cleaner and more semantic HTML by avoiding attributes that are not widely supported or could lead to unpredictable behaviour across different screen readers and assistive technologies.
-
Facilitates codebases to be more aligned with accessibility guidelines like WCAG (Web Content Accessibility Guidelines), potentially improving a website’s legal compliance with accessibility standards and enhancing its usability for all users.
Disallow aria-hidden="true"
from being set on focusable elements.
<button aria-hidden="true" onClick={() => console.log('Button clicked')}>
Click me!
</button>
-
This rule directly impacts web accessibility by ensuring that focusable elements, such as buttons or links, are not hidden from assistive technologies with
aria-hidden="true"
. Making focusable elements perceivable by users who rely on screen readers and other assistive tools is crucial for inclusive design. -
By disallowing the
aria-hidden="true"
attribute on focusable elements, this rule helps maintain a logical navigation order for keyboard users. Focusable elements that are visually hidden but not from assistive technologies can confuse keyboard-only users when tabbing through a website. -
The rule enforces better HTML semantics and ARIA (Accessible Rich Internet Applications) practices. Since
aria-hidden="true"
is meant to hide elements from the accessibility tree, using it on elements meant to be interactive contradicts its intended purpose. Thus, adherence to this rule leads to cleaner, more semantically correct code. -
This ESLint rule assists in automatic code review processes, enabling developers to catch and correct accessibility issues early in the development cycle. Automated checks for such accessibility pitfalls reduce the risk of these issues making it into production, thus improving the overall quality of the website or application.
Enforce autoFocus prop is not used.
import React from 'react';
function LoginForm() {
return (
<input autoFocus type="text" name="username" placeholder="Username" />
);
}
-
This ESLint rule helps in promoting accessible web development practices by discouraging the use of the
autoFocus
prop on elements. The autoFocus prop can negatively impact users with disabilities, as it might lead to an unexpected change in the focus, making navigation confusing for screen reader users and those with cognitive disabilities. -
By enforcing developers to not use the
autoFocus
prop directly and instead consider alternative, more accessible solutions, such as conditionally focusing an element based on user actions or component states, it encourages a more thoughtful approach to setting focus that respects the user’s intention and control. -
This rule includes an option to ignore non-DOM elements, acknowledging that not all elements using the autoFocus prop might have an impact on accessibility or be relevant. This distinction ensures that the rule is applied only where it can genuinely improve accessibility, avoiding unnecessary reports in cases where autoFocus usage does not affect the accessibility of web components.
-
The suggested fix using
useRef
anduseEffect
in React for focusing elements programmatically demonstrates an accessible alternative to autoFocus. It provides developers with a practical, accessible method to set focus when necessary, such as focusing on an input field when a form is shown, without automatically moving focus as soon as the component mounts. This approach offers a balance between usability and accessibility, ensuring that focus management is done in a user-friendly and A11Y-compliant manner.
Enforce distracting elements are not used.
import React from "react";
function DistractingComponent() {
return (
<div>
<marquee>Welcome to my website!</marquee>
</div>
);
}
-
Enhances Accessibility: By discouraging the use of elements that can be distracting, such as
<marquee>
or<blink>
, it makes web content more accessible to users with attention disorders or visual impairments, adhering to Web Content Accessibility Guidelines (WCAG). -
Improves User Experience: Distracting elements can negatively affect the user’s ability to focus on the main content. By enforcing this rule, developers create a smoother, less disruptive web experience, which is beneficial for all users, but especially critical for maintaining the attention of those with cognitive limitations.
-
Ensures Modern Web Practices: The rule encourages the use of modern, standard-compliant HTML and CSS techniques for animations or highlighting important information instead of outdated and obsolete elements, leading to more maintainable and future-proof codebases.
-
Customizable Enforcement: Given that the rule allows for configuration through options, it provides flexibility. Teams can tailor the rule to suit their specific needs or accessibility standards, ensuring that enforcement aligns with their web development practices and objectives, thus fostering a more inclusive web environment without sacrificing brand or creative goals.
Interactive elements should not be assigned non-interactive roles.
import React from 'react';
const BadExample = () => {
return (
<button role="none">Click Me</button>
);
};
- This rule helps ensure that interactive elements such as buttons maintain their inherent semantics, which is crucial for accessibility. By preventing interactive elements from being assigned non-interactive roles, it aids users who rely on assistive technologies to navigate and interact with web content more effectively.
- It promotes better accessibility practices by enforcing the correct use of ARIA roles. Since ARIA roles can change the way an element is announced or interacted with by assistive technologies, incorrectly changing an interactive element to a non-interactive role could lead to confusion and a degraded user experience for people with disabilities.
- The rule can prevent common mistakes in assigning roles that contradict the native semantic meaning of elements. For example, assigning the role “none” to a button element, as shown in the provided example, removes the interactive nature of the button, which could lead to a situation where the element is no longer focusable or interactive, impacting users who navigate via keyboard or assistive technologies.
- By allowing overrides from rule configuration for specific elements and roles, the rule provides flexibility to developers. They can adjust the rule for cases where a deviation is necessary and justified, ensuring that the linting process does not enforce a one-size-fits-all approach but rather accommodates the nuanced requirements of complex web applications.
Non-interactive elements should not be assigned mouse or keyboard event listeners.
<div onClick={() => console.log('Clicked!')}>
Click me!
</div>
- Enhances web accessibility by ensuring that non-interactive elements, such as
<div>
s, do not have mouse or keyboard event listeners, pushing for the use of semantically correct interactive elements like<button>
. - Aids in creating more predictable and user-friendly interfaces for assistive technologies, as these tend to rely on the semantic structure of HTML to navigate and interact with content.
- Helps in maintaining clean and semantic HTML, which contributes to better SEO and easier maintainability of the code by clearly distinguishing between interactive and non-interactive elements.
- Prevents potential confusion for users who might expect certain behaviors from interactive elements, ensuring that elements like
<div>
or<span>
which are not traditionally clickable do not perform interactive roles without proper roles and attributes.
Non-interactive elements should not be assigned interactive roles.
function MyComponent() {
return (
<ul>
<li role="button" onClick={() => console.log('Clicked!')}>
Click me
</li>
</ul>
);
}
- This rule ensures adherence to web accessibility standards by preventing non-interactive elements, such as
<li>
tags, from being assigned interactive roles, such asbutton
, which can confuse assistive technologies and users about the element’s functionality. - By enforcing the correct use of interactive roles on appropriate elements, this rule promotes the creation of user interfaces that are accessible to individuals relying on screen readers or other assistive technologies, thereby enhancing overall user experience.
- The rule promotes semantic HTML practices by ensuring that interactive behaviors are assigned to elements that are inherently designed to be interactive, such as
<button>
, rather than repurposing non-interactive elements through roles and event listeners, leading to cleaner and more maintainable code. - It provides an opportunity for developers to reevaluate the structure of their markup and consider alternatives, such as using native HTML elements with built-in accessibility features, thereby encouraging the development of web applications that are both accessible and in compliance with modern web standards.
tabIndex
should only be declared on interactive elements.
// Bad example: Non-interactive element with tabIndex
const NonInteractiveWithTabIndex = () => {
return (
<div tabIndex="0">
I am focusable but not interactive
</div>
);
};
- It enforces better accessibility practices by ensuring that elements with a
tabIndex
are indeed interactive, as non-interactive elements with a focusable state can confuse users navigating a site with assistive technologies. - The rule specifically checks if non-interactive elements are incorrectly assigned a
tabIndex
, helping developers catch and correct potential mistakes that could lead to a poor user experience for people relying on keyboard navigation. - By allowing configuration overrides based on tags, roles, and allowance for expression values, it offers flexibility for developers to fine-tune the rule to accommodate valid use cases where non-standard elements might need to be focusable.
- This rule contributes to the development of more semantic HTML and web content, encouraging the use of correct elements for interactive tasks (e.g., using
<button>
over<div>
with atabIndex
for clickable elements), which is a key principle of web accessibility.
Enforce usage of onBlur
over onChange
on select menus for accessibility.
import React from 'react';
function Dropdown() {
return (
<select onChange={(e) => console.log("Changed to:", e.target.value)}>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
);
}
- Enforces better accessibility practices by prompting developers to use
onBlur
instead ofonChange
for select elements, which can prevent unexpected behavior for keyboard and screen reader users. This adaptation aims to enhance the interaction experience for users relying on assistive technologies. - Addresses a common accessibility issue where
onChange
can cause issues in certain assistive technologies by triggering changes as soon as the selection is changed, which might not be the user’s intent.onBlur
, on the other hand, waits until the element loses focus, aligning actions more closely with user intentions. - Helps in maintaining a consistent development approach towards accessible web applications by automatically identifying and suggesting corrections for easily overlooked accessibility concerns related to form elements, thus improving the overall quality and usability of web applications for a diverse range of users.
- Supports automated code review and refactoring processes by providing specific, actionable feedback regarding the use of
onChange
without a correspondingonBlur
handler on select elements, thereby aiding in the swift correction of accessibility flaws in existing and new codebases.
Enforce explicit role property is not the same as implicit/default role property on element.
import React from 'react';
function Navigation() {
return (
// The nav element implicitly has a role of "navigation", thus explicitly setting it is redundant.
<nav role="navigation">
{/* Navigation links */}
</nav>
);
}
export default Navigation;
-
The rule ensures that the code is cleaner by avoiding redundancy. In the example, explicitly setting the role of a
<nav>
element to “navigation” is redundant since “navigation” is already its implicit role. By removing such redundancies, the code becomes easier to read and maintain. -
It enforces best practices in accessibility. While it might seem harmless to reiterate the role of an element, doing so can potentially lead to confusion for developers who may not be as familiar with the implicit roles of HTML elements. This rule educates developers about these implicit roles, contributing to a more universally accessible web.
-
The rule can potentially highlight misunderstandings or misuses of the role attribute. For instance, if a developer explicitly sets a role that’s identical to the implicit role of an element, it might indicate a lack of understanding of ARIA roles or HTML semantics. Identifying these instances can serve as teaching moments.
-
It improves performance optimally. While the direct impact on performance might be minimal, any practice that reduces unnecessary attributes in the DOM can contribute to faster rendering. By enforcing the elimination of redundant roles, this rule helps keep the HTML output lean, which is especially beneficial for users on low-bandwidth connections or older devices.
Enforce that non-interactive, visible elements (such as <div>
) that have click handlers use the role attribute.
<div onClick={() => console.log('clicked')}>
Click me
</div>
-
Ensures accessibility for users relying on assistive technologies: By enforcing non-interactive elements like
<div>
with click handlers to have arole
attribute, it makes these elements perceivable and usable for users navigating via screen readers or other assistive devices. -
Promotes semantic HTML: Even though certain elements are being used in an interactive manner, HTML5 might not always offer a semantic element that fits the use case. Adding roles to elements like
<div>
used as buttons helps communicate the intended behavior semantically, improving code clarity and maintainability. -
Helps maintain consistency in user interface design: By enforcing roles on elements that are interacted with, this rule assists in creating a consistent approach to how interactions are handled across the website or application. This consistency is crucial for user experience, making interactions predictable across different parts of the application.
-
Facilitates automated testing and quality assurance: By clearly marking interactive elements with roles, it becomes easier to target these elements in automated tests. This can improve the quality assurance process, ensuring that interactive elements are accessible and function as intended across updates and changes to the site or application.
Enforces using semantic DOM elements over the ARIA role
property.
function MyComponent() {
return <div role="button" onClick={() => console.log("Clicked!")}>Click me</div>;
}
-
The rule focuses on enhancing accessibility by promoting the use of semantic HTML elements. Using appropriate tags (e.g.,
<button>
instead of<div role="button">
) helps users with assistive technologies understand and navigate the content more effectively. -
It encourages developers to adhere to semantic HTML practices by automatically identifying instances where a non-semantic element is used with an ARIA role that has a semantically appropriate HTML counterpart. This direct mapping ensures that the solutions are not only accessible but also cleaner and more in line with web standards.
-
This rule aids in reducing the complexity of the codebase. By replacing elements with unnecessary roles with their semantic equivalents, the code becomes more straightforward and maintainable. This is because semantic HTML is inherently more descriptive and easier to understand than spans or divs with added roles and functionality.
-
Implementing this rule can improve the performance of web applications on assistive devices. Semantic HTML elements come with built-in accessibility features that are optimized for performance, unlike ARIA roles that might require additional processing. This can lead to a smoother and more efficient experience for users relying on screen readers and other assistive technologies.
Enforce that elements with ARIA roles must have all required attributes for that role.
import React from 'react';
function BadCheckbox() {
return (
<input type="button" role="checkbox" />
);
}
- Ensures accessibility by enforcing that elements with ARIA roles have the appropriate attributes necessary for assistive technologies to convey the element’s purpose and state accurately, as shown by the rule identifying missing
aria-checked
attribute in elements withrole="checkbox"
. - Improves code maintainability and decreases the likelihood of accessibility regressions by automatically identifying elements that are missing required ARIA attributes specific to their role, thereby facilitating easier identification and correction of potential accessibility issues.
- Promotes adherence to web accessibility standards (specifically ARIA specifications) by ensuring elements with roles contain all necessary attributes, thereby helping in making web applications more accessible to users with disabilities.
- Enhances user experience for individuals relying on assistive technologies by ensuring interactive elements are correctly identified and their state is accurately communicated, as demonstrated by the addition of
aria-checked="false"
to make the role of the element clear and operable.
Enforce that elements with explicit or implicit roles defined contain only aria-*
properties supported by that role
.
function BadButton() {
return (
<div role="button" aria-labelledby="id1">Click Me</div>
);
}
- This rule aids in ensuring that ARIA (Accessible Rich Internet Applications) properties used in JSX elements are appropriate for their specified roles, which strengthens web accessibility by helping assistive technologies to better understand and interact with the content.
- By enforcing elements to contain only supported
aria-*
properties for their role, it prevents developers from mistakenly using ARIA attributes that are not applicable to the element’s role, which could otherwise lead to confusion for users of assistive technology. - The rule includes logic to handle both explicit roles (defined by the
role
attribute) and implicit roles (determined by the element type and its context), which is crucial because it covers a wider range of scenarios, ensuring that even elements without an explicitly set role follow the ARIA properties guidelines. - It focuses on preventing the use of invalid
aria-*
properties for a given role by comparing the used properties against a set of supported properties for the detected role. This targeted approach helps in catching and mitigating common accessibility issues at the development stage, contributing to a more accessible web.
Enforce scope
prop is only used on <th>
elements.
import React from 'react';
const TableComponent = () => (
<table>
<tbody>
<tr>
{/* Incorrect use of `scope` on `<td>` element */}
<td scope="col">Name</td>
<td>John Doe</td>
</tr>
</tbody>
</table>
);
export default TableComponent;
- Using this ESLint rule promotes web accessibility by ensuring that the
scope
attribute is correctly applied to table headers (<th>
elements), which helps screen readers and other assistive technologies understand the structure of the data, improving the experience for users with disabilities. - The rule prevents a common mistake of incorrectly using the
scope
attribute on elements other than<th>
, such as<td>
, which could lead to misleading information being presented to assistive technologies, thus avoiding confusion and making the content more accessible and semantically correct. - Enforcing this rule helps maintain consistency across the codebase regarding the usage of the
scope
attribute, making it easier for developers to follow best practices in web development without having to remember specific accessibility guidelines, thus ensuring a higher quality of code. - By automatically identifying and flagging incorrect uses of the
scope
attribute, this rule saves developer time and reduces the likelihood of accessibility defects being introduced during development, leading to a more efficient development process and reducing the need for extensive accessibility audits later on.
Enforce tabIndex
value is not greater than zero.
// Bad Code Example
import React from 'react';
const MyButton = () => {
return (
<button tabIndex="1">Click Me</button>
);
};
- Ensuring
tabIndex
values do not exceed zero is essential for creating a web navigation structure that is logical and predictable. Positive values can disrupt the natural order of keyboard navigation, leading to a confusing experience for users who rely on assistive technologies. - This rule helps maintain consistency in the keyboard focus flow throughout a web application. By enforcing a
tabIndex
of zero or negative, developers are encouraged to rely on the natural DOM order for keyboard navigation, which is generally more intuitive and accessible. - The rule’s focus on literal values for
tabIndex
means it specifically targets easily identifiable and correctable instances where thetabIndex
might be improperly set. This clarity can expedite the process of identifying and addressing accessibility issues related to focus management. - By automatically flagging elements with a positive
tabIndex
for review, this ESLint rule can serve as an educational tool for developers, highlighting an often-overlooked aspect of accessible web design. As developers adjust their coding practices to comply with this rule, they inherently learn more about accessible web development principles.