Get Started
- CodeAnt AI
- Control Center
- Pull Request Review
- IDE
- Compliance
- Anti-Patterns
- Code Governance
- Infrastructure Security Database
- Application Security Database
React
Enforces consistent naming for boolean props
import PropTypes from 'prop-types';
function MyComponent({ isEnabled }) {
if (isEnabled) {
return <div>Feature is enabled</div>;
}
return <div>Feature is disabled</div>;
}
MyComponent.propTypes = {
isEnabled: PropTypes.bool
};
-
Enforces the use of clear and descriptive names for boolean props in React components, which helps in understanding the purpose of the prop without needing additional context. This specificity avoids confusion, especially in larger projects with many components.
-
By establishing a naming convention for boolean props, such as prefixing with “is” or “has”, the rule promotes consistency throughout the application. This consistency aids in readability and maintainability, making it easier for new developers to understand the codebase.
-
Helps in catching potential errors during development, such as typos or incorrect prop names, by enforcing a specific naming pattern. This can prevent bugs that are hard to track down, arising from misinterpreted prop purposes or values.
-
Supports better documentation practices by encouraging the definition of props in a self-explanatory manner. When boolean props are named clearly, documentation can be more straightforward, benefiting both the development and usage of component libraries within teams or publicly.
Disallow usage of button
elements without an explicit type
attribute
// In JSX
<button onClick={handleClick}>Click me</button>
// Using React.createElement
React.createElement('button', { onClick: handleClick }, 'Click me');
- Ensures consistency in the button element’s behavior across different browsers. Without a specified
type
attribute, different browsers may default the button to different types, leading to inconsistent behavior. - Prevents accidental submissions in forms. If a button is placed within a form without a type explicitly set to
button
, it might inadvertently act as a submit button, causing unexpected form submissions. - Enhances code readability and maintainability. By explicitly requiring a
type
attribute for button elements, developers are encouraged to think about and document the specific role of each button in the UI, leading to more readable and maintainable code. - Aligns with best practices in web development. Explicitly defining the type of a button element is a norm widely recognized in web development for creating predictable and accessible user interfaces. This rule helps enforce this best practice systematically across a codebase.
Enforce all defaultProps have a corresponding non-required PropType
import PropTypes from 'prop-types';
class MyComponent extends React.Component {
// Code here...
}
MyComponent.defaultProps = {
someProp: 'default value', // This will trigger the ESLint rule since someProp is not declared in propTypes.
};
- Ensures consistency between
defaultProps
andpropTypes
, encouraging developers to explicitly declare props that have defaults, thereby improving code readability and maintainability. This rule helps prevent cases wheredefaultProps
are defined for props that are not declared inpropTypes
, which can lead to confusion about the expected props for a component. - Enhances type safety in React components by ensuring that every prop with a default value also has a type definition. This tight coupling between default values and prop types aids in catching potential type mismatches or errors at development time rather than runtime.
- Promotes best practices in component API design by requiring developers to think about and define the type of each prop, including those with default values. This leads to more deliberate and self-documenting code, making it easier for new developers to understand the component’s expected props and their types.
- Helps in the automatic documentation generation process where tools may rely on propTypes definitions to generate prop tables. Without corresponding propTypes for defaultProps, the documentation might be incomplete or misleading, potentially leading to incorrect usage of components.
Enforce consistent usage of destructuring assignment of props, state, and context
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
- This rule encourages the consistent usage of destructuring for props, making the component’s code more readable and maintainable by clearly showing which props are being used at the beginning of the function or method.
- It helps in reducing the redundancy of typing
this.props
orthis.state
multiple times, which not only makes the code cleaner but also potentially reduces the size of the compiled code. - By enforcing destructuring, it implicitly encourages developers to consider which properties they actually need, potentially leading to components that are less dependent on the entire props or state object, thus promoting more modular and reusable code components.
- Implementing this rule can improve performance slightly in some cases. Destructuring allows properties to be stored in locally scoped variables, which can be faster to access than repeatedly accessing properties on
this.props
orthis.state
, especially in deeply nested structures.
Disallow missing displayName in a React component definition
import React from 'react';
const MyComponent = () => {
return <div>Hello, World!</div>;
};
- This rule helps in clearly identifying React components in the React Developer Tools, making debugging easier by displaying a meaningful name instead of a generic or anonymized one.
- It promotes better practices for component definition by ensuring that each component has a distinguishable identity, thus improving code readability and maintainability, especially in large projects where component names can help in tracing their usage and purpose.
- By enforcing a displayName for each component, it aids in better documentation and tooling support, as many automated documentation tools rely on component names to generate accurate and useful documentation.
- This rule can be particularly helpful in projects that utilize higher-order components or dynamically generate components, as these patterns can obscure the component’s real name, making the codebase harder to navigate and understand without explicit display names.
Disallow certain props on components
import React from 'react';
function App() {
return (
<div>
{/* This `className` usage on CustomButton is against the eslint rule */}
<CustomButton className="special-button">Click Me</CustomButton>
</div>
);
}
export default App;
-
Enforces consistent prop usage across components by disallowing certain props, promoting a uniform prop design philosophy and preventing the misuse of props that can lead to unexpected behaviors or styling issues. For example, forbidding the use of
className
on aCustomButton
component encourages using a designated prop likevariant
for styling variations, aligning with design systems and component libraries. -
Enhances code readability and maintenance by standardizing how features and styles are applied to components. Instead of using general-purpose props like
className
orstyle
, which can lead to diverse implementations and make the codebase harder to maintain, it requires developers to use more descriptive props such asvariant
. This specificity can make the code easier to understand and maintain over time. -
Helps with the enforcement of security best practices in some cases. For instance, prohibiting certain props such as
dangerouslySetInnerHTML
on components directly can mitigate the risk of cross-site scripting (XSS) attacks by encouraging the use of safer alternatives or patterns to accomplish similar functionality. -
Provides clear and customizable feedback to developers through configuration options and custom messages. This rule allows specifying detailed messages for forbidden props, making it easier for developers to understand why a prop is disallowed and what alternatives to use. As a result, it not only prevents unwanted prop usage but also educates developers about best practices and the specific code standards of a project.
Disallow certain props on DOM Nodes
// Bad usage of direct style prop on DOM element
function BadComponent() {
return (
<div style={{ fontSize: '16px' }}>This is a bad practice example.</div>
);
}
- The rule specifically targets the use of certain properties (props) on DOM nodes within React JSX, enforcing a cleaner, more maintainable approach to manipulating elements. This focus ensures DOM manipulation practices align with React’s declarative nature and promotes the usage of CSS for styling over inline styles, which can lead to harder-to-maintain codebases.
- By allowing the configuration of forbidden props, this rule gives teams the flexibility to tailor the rule to their project’s specific needs or coding standards. This means that teams can decide, for example, to forbid the use of inline styles (
style
prop) or direct manipulation of certain attributes that might lead to security vulnerabilities, such asinnerHTML
, enhancing both the maintainability and security of the code. - The rule provides a mechanism for custom error messages to be configured and displayed when a forbidden prop is used. This not only helps to catch potentially problematic code but also educates developers on why a certain prop is discouraged, fostering a learning environment and encouraging best practices within the team.
- By disallowing certain props on DOM nodes, this rule implicitly encourages developers to embrace more React-centric solutions, such as using CSS modules or styled-components for styling, thus leveraging React’s component-based architecture. This results in a more consistent and scalable codebase that better leverages React’s strengths and ecosystem.
Disallow certain elements
import React from 'react';
function App() {
return <div className="app">Hello, world!</div>;
}
- Prevents the use of potentially unsafe or deprecated HTML elements in React projects, which can improve code quality and maintainability by ensuring that developers are only using elements that adhere to best practices.
- Enables teams to enforce consistency across the codebase by disallowing certain elements that have been decided against in project standards, making the code easier to read and understand for new team members.
- Customizable through configuration to adapt to specific project needs or coding guidelines, allowing teams to specify which elements should be forbidden and include custom messages to help developers understand why an element is disallowed.
- Helps in gradually refactoring existing codebases by identifying and reporting the usage of forbidden elements, guiding developers towards using preferred alternatives and incrementally improving the project’s overall architectural choices.
Disallow using another component’s propTypes
import React from 'react';
import PropTypes from 'prop-types';
import AnotherComponent from './AnotherComponent';
class SomeComponent extends React.Component {
// Using AnotherComponent's propTypes directly is not advisable
static propTypes = {
...AnotherComponent.propTypes,
extraProp: PropTypes.string
};
render() {
// Component implementation
}
}
export default SomeComponent;
- Prevents tight coupling between components by discouraging the direct reuse of another component’s propTypes, which promotes better maintainability and reduces the risk of unintended effects when propTypes of the reused component change.
- Encourages developers to explicitly define propTypes within each component, leading to clearer documentation and understanding of component APIs, making the codebase more readable and easier to work with for current and future developers.
- Aids in catching potential errors during development by ensuring that developers consciously think about and define the props their component expects, rather than blindly inheriting them, thus potentially reducing bugs related to unexpected prop types.
- Promotes the principle of encapsulation in component design by ensuring components define their own propTypes rather than relying on external definitions, thus making each component more self-contained and easier to refactor or replace.
Disallow certain propTypes
import PropTypes from 'prop-types';
const UserProfile = (props) => {
return <div>{props.name}</div>;
};
UserProfile.propTypes = {
id: PropTypes.any,
name: PropTypes.string,
data: PropTypes.object,
history: PropTypes.array,
};
export default UserProfile;
-
This rule enforces the use of more specific
propTypes
rather than generic types likeany
,object
, orarray
, which improves the component’s prop validation, making it clearer to other developers what type of data should be passed to a component. For instance, usingPropTypes.shape
instead ofPropTypes.object
provides a detailed structure of the expected prop. -
By disallowing certain propTypes, it pushes for a better documentation and understanding of component props, which is beneficial for maintenance and readability. For example, replacing
PropTypes.any
withPropTypes.number
explicitly states the expected type, removing ambiguity and potential misuse of the component. -
It helps prevent runtime errors by enforcing stricter type checking at compile time. If a developer tries to pass a data type that is not expected by the component, it will be easier to catch these errors early in the development process due to the specific propTypes definitions.
-
It encourages the adoption of best practices in defining component interfaces clearly. Instead of using generic types that can accept any kind of data, defining explicit types ensures that components are used as intended, leading to more robust and predictable code.
Enforce a specific function type for function components
import React from 'react';
// Bad: Function component defined as a function declaration
function MyComponent(props) {
return <div>Hello, {props.name}!</div>;
}
- Promotes consistency in function component definitions across the codebase by enforcing a single, specific function type, which aids in readability and maintainability.
- Arrow functions in React can lead to shorter and more concise syntax, which can improve the development experience by making the code more elegant and easier to understand at a glance.
- Enforcing arrow functions for functional components can potentially reduce the likelihood of
this
keyword misuse, as arrow functions do not have their ownthis
context, which aligns well with the functional component paradigm in React. - By advocating for a specific function type, the rule indirectly encourages the use of functional components over class components, aligning with modern React best practices that favor functional components for their simplicity and hook support.
Ensure destructuring and symmetric naming of useState hook value and setter variables
import React, { useState } from 'react';
function Counter() {
const [value, updateValue] = useState(0); // Bad because name of setter does not reflect its state variable
return (
<div>
{value}
<button onClick={() => updateValue(value + 1)}>Increment</button>
</div>
);
}
- Encourages a consistent naming convention for state variables and their setter functions in React functional components, which improves readability and maintainability of code. Specifically, it promotes a pattern where the setter function’s name is clearly derived from the state variable it is meant to update.
- Helps to avoid confusion and errors in large components or projects by ensuring that the relationship between a state variable and its corresponding setter function is easily recognizable, thus making the code easier to understand and debug.
- Increases the efficiency of code reviews and collaboration among team members by establishing a clear and predictable pattern for naming useState variables and their setters. This makes it easier for others to quickly understand the component’s state management logic without needing to delve into the specifics of each useState call.
- Reduces the likelihood of bugs that can occur when developers mistakenly use the wrong setter function for a state variable, due to unclear or inconsistent naming. By adhering to a symmetric naming convention, it becomes instantly clearer which setter function is associated with which state variable, thus minimizing such errors.
Enforce sandbox attribute on iframe elements
import React from 'react';
class MyComponent extends React.Component {
render() {
return (
<div>
<iframe src="https://www.example.com"></iframe>
</div>
);
}
}
-
This rule specifically enforces the inclusion of the sandbox attribute in iframe tags within React JSX to ensure that iframes are embedded with an additional layer of security. The sandbox attribute restricts the iframe’s abilities (like running scripts or submitting forms) unless explicitly allowed, reducing the risk of security vulnerabilities.
-
By mandating the sandbox attribute through this rule, it encourages developers to consciously decide which actions should be permitted by the embedded content. This promotes a principle of least privilege, enhancing the security posture of the application by preventing malicious activity through iframes.
-
The rule detects the absence of the sandbox attribute both in JSX syntax and when iframes are created dynamically using
React.createElement
. This comprehensive approach ensures that all iframes, irrespective of their creation method, are evaluated, leaving no room for inadvertently omitting the sandbox attribute in dynamically generated content. -
The inclusion of this rule in ESLint configurations aids in early detection and correction of missing sandbox attributes during the development process. This proactive security measure can prevent potential security flaws from reaching production, thus safeguarding both the application and its users from common attack vectors associated with iframes.
// Importing a Button component but not clear about the exact file, bad practice if we want explicitness.
import { Button } from './components';
- Encourages explicit import paths which enhance code readability and clarity, making it easier for developers to understand from where exactly the
Button
component is imported without digging into thecomponents
directory structure. - Prevents potential errors or conflicts that may arise if there are multiple components with the same name in different files within the
components
directory. By specifying the exact file, developers can ensure they are importing the correctButton
component. - Improves maintainability of the codebase by promoting a clear and consistent import pattern. When files are moved or renamed, explicit imports will break explicitly, making such changes easier to track and update compared to index imports, which might silently fail or import the wrong component.
- Facilitates better tooling support, such as automatic dependency analysis, easier refactoring, and more accurate code navigation features (e.g., “go to definition”) in IDEs, because the import path is unambiguous and directly points to the specific file.
Enforce boolean attributes notation in JSX
// Bad code example with explicit boolean value
function App() {
return <MyComponent isEnabled={true} />;
}
-
This ESLint rule promotes a consistent coding style within JSX by enforcing or forbidding the explicit declaration of boolean attributes as
true
. Specifically, it can automate the removal or addition of={true}
for boolean attributes depending on the chosen configuration (ALWAYS
orNEVER
), making the codebase more uniform. -
Enforcing this rule can help improve readability and succinctness of JSX code. For example,
<MyComponent isEnabled />
is easier and quicker to read and understand than<MyComponent isEnabled={true} />
, especially in larger components or when multiple boolean props are involved. -
It can prevent common mistakes due to misunderstanding or misuse of JSX boolean attributes. Some developers may erroneously believe that omitting the value (thus implicitly setting it to
true
) has a different effect than explicitly setting it totrue
, or vice versa. Standardizing this aspect across the project helps avoid such confusion. -
The rule offers automatic fix capabilities, significantly reducing the manual effort required to adhere to this stylistic preference. Developers can rely on automated tools to adjust their code format according to this rule, rather than doing it manually, which saves time and minimizes human error.
Enforce or disallow spaces inside of curly braces in JSX attributes and expressions
const Greeting = () => (
<div>
Hello, { name }!
</div>
);
- This rule enforces a consistent coding style by either requiring or disallowing spaces inside curly braces in JSX attributes and expressions, which improves the readability and maintainability of the code by ensuring a consistent appearance.
- It helps in catching unintentional space characters that could potentially lead to errors in dynamic expressions or when passing props, ensuring the integrity and expected behavior of the React components.
- The rule’s focus on maintaining spacing consistency specifically within JSX enables developers to quickly identify elements and expressions, making the code easier to understand and navigate, especially for those who are new to a project or less familiar with React.
- By programmatically enforcing these stylistic guidelines, the rule eliminates the need for manual code reviews for this aspect, saving time and reducing the likelihood of human error, thus streamlining the development process.
Enforce closing bracket location in JSX
const element = (
<MyComponent prop1="value1"
prop2="value2"
/>
);
- This rule helps ensure a consistent location for JSX closing brackets, which can improve readability and maintainability by making the code structure more predictable across different components and projects.
- By allowing customization of where the closing bracket is placed (e.g., aligned with the opening tag, after the last prop, etc.), it accommodates various coding styles and preferences, thereby increasing flexibility for teams to adopt a style that suits their workflow best.
- The rule mitigates common formatting errors, such as misaligned brackets, by automatically detecting and suggesting fixes. This can save developers time during code reviews and reduce the cognitive load when parsing through JSX structures.
- It supports automatic fixing capability, which means developers can correct violations without manual intervention, streamlining the development process and ensuring code style consistency without extra effort.
Enforce closing tag location for multiline JSX
const MyComponent = () => (
<div>
<span>
Some content
</span
>
</div>
);
-
Ensures consistent readability and structure in JSX code by enforcing that closing tags either align with the opening tags or start on a new line if the element spans multiple lines. This rule helps maintain a clean and organized codebase, which is particularly beneficial in larger projects or when working within a team, as it makes the JSX easier to read and understand.
-
Prevents common syntax errors in JSX by ensuring that closing tags are correctly placed. Improperly placed closing tags can lead to unexpected behaviors or compilation errors. By enforcing a specific closing tag location, developers are less likely to introduce such errors, thus reducing debugging time and improving overall code quality.
-
Facilitates easier code maintenance and refactoring by enforcing a uniform structure. When all team members follow the same rule for closing tag locations, it becomes quicker and more efficient to modify existing code. Consistency in code style reduces the cognitive load when switching between different parts of the codebase, making it more approachable for new team members or contributors.
-
Enhances automated code formatting and linting tools’ effectiveness by providing a specific, enforceable rule regarding JSX structure. This allows such tools to automatically correct minor formatting issues without human intervention, further streamlining the development process and ensuring that code adheres to predefined standards with minimal effort.
Disallow unnecessary JSX expressions when literals alone are sufficient or enforce JSX expressions on literals in JSX children or attributes
const MyComponent = () => {
return (
<div>
{"This is an unnecessary use of curly braces."}
<button title={"Unnecessary description"}>
Click Me
</button>
</div>
);
};
- Ensures consistency in the use of curly braces in JSX, thereby improving code readability and maintenance. It prevents the unnecessary use of JSX expressions for string literals that can be directly inserted, making the JSX cleaner and easier to understand.
- Helps in catching potential bugs early in the development process by enforcing explicit usage of curly braces or literals, depending on the rule configuration. This strictness can prevent subtle mistakes related to the rendering of values in JSX.
- Reduces the cognitive load on developers when reading the code by enforcing a uniform style. By minimizing unnecessary JSX expressions, developers can more easily discern when a value is a static string versus a dynamic expression.
- Automates the process of optimizing JSX syntax through fixable warnings, allowing developers to easily adhere to best practices without manual effort. This automation ensures that codebase quality is maintained without adding to the developers’ workload.
Enforce consistent linebreaks in curly braces in JSX attributes and expressions
import React from 'react';
const MyComponent = () => (
<div>
<p>{`This is a
multiline text`}</p>
<p>{`This is a singleline text`}</p>
</div>
);
- It promotes readability and consistency by enforcing a standardized approach to newline usage within JSX curly braces, making code easier to read and understand, especially in projects with multiple contributors.
- The rule helps in distinguishing between multiline and singleline JSX expressions or attributes, ensuring that multiline expressions are more visually separated from their enclosing tags or components, which can help in identifying the scope and structure of JSX code more easily.
- By providing options to require, forbid, or ensure consistency of newlines, it allows teams to adapt the rule to their specific coding style and preferences, thus supporting a diverse range of project guidelines and enhancing team collaboration.
- Automatically fixable cases (where no comments exist between the curly braces and the content) allow for easy codebase-wide adjustments, saving developer time during both initial development and subsequent code reviews or refactoring phases, leading to a more efficient development process.
Enforce or disallow spaces inside of curly braces in JSX attributes and expressions
import React from 'react';
const Greet = () => {
const name = 'John';
return (
<div>
{ name } {/* Bad: spaces inside curly braces */}
<h1>{name }</h1> {/* Bad: space before closing brace */}
<h2>{ name}</h2> {/* Bad: space after opening brace */}
</div>
);
};
export default Greet;
- By enforcing or disallowing spaces inside of curly braces in JSX attributes and expressions, this rule brings consistency to the codebase, making it easier for developers to read and maintain code. It eliminates the subjective stylistic choices, leading to a uniform code style throughout the project.
- The rule allows configuration to cater to different project styles (e.g., always having spaces inside curly braces or never), thus providing flexibility. This means teams can tailor the rule to match their coding standards, ensuring all developers write code in a consistent manner aligned with project guidelines.
- With its automatic fix functionality, developers can quickly correct spacing issues within JSX curly braces without manually adjusting spaces. This can significantly speed up the development process and reduce the time spent on code formatting, allowing developers to focus on more complex problems.
- By explicitly handling multiline expressions differently, if configured to do so, the rule helps in maintaining readability in complex JSX code. This is particularly useful in large projects where JSX expressions can become nested and complicated, making it essential to have clear spacing rules to keep the code understandable.
Enforce or disallow spaces around equal signs in JSX attributes
// For "never" option, having spaces is incorrect
const element = <Component prop = {value} />
// For "always" option, not having spaces is incorrect
const element = <Component prop={value} />
- This ESLint rule helps to maintain consistency in the codebase regarding how JSX attributes are formatted, specifically focusing on the spacing around equal signs. This can make the code more readable and easier to understand at a glance, especially for new team members or when returning to a project after some time.
- It offers flexibility to teams or projects to enforce their preferred style (either having spaces around equal signs in JSX attributes or not) by configuring the rule as either ‘never’ or ‘always’. This allows the rule to adapt to different coding standards and preferences, ensuring that the developers do not have to manually adjust their code style.
- The rule includes automatic fixers that can correct the spacing around equal signs according to the specified configuration. This reduces the effort required from developers to adhere to the coding standards and can significantly speed up the process of formatting code correctly during both development and code review phases.
- By enforcing this rule, it can help prevent minor but common syntax inconsistencies that might otherwise slip through during code reviews. Automating the enforcement of such stylistic preferences allows developers to focus their attention on more significant issues in the code, such as logic errors or performance optimizations, thereby improving the overall quality of the codebase.
Disallow file extensions that may contain JSX
// Button.js (incorrect extension according to the rule configuration)
import React from 'react';
const Button = () => (
<button>Click me</button>
);
export default Button;
-
It enforces consistency in the file extensions used for files containing JSX syntax, which can help in project maintainability by ensuring that all JSX files follow the same naming convention. This can make it easier for developers to understand which files contain JSX and which do not at a glance.
-
By disallowing file extensions that may contain JSX unless configured otherwise, it helps in clearly distinguishing between files that use JSX and those that do not. This can be particularly useful in projects that use both React (or other libraries that use JSX) and non-React JavaScript files, reducing the cognitive load on developers when navigating the project.
-
The rule provides a configuration option to enforce the usage of a specific extension only when needed (
as-needed
option). This flexibility allows for a stricter enforcement in projects where JSX is not ubiquitous, ensuring that developers only use the JSX-specific extensions for files that actually contain JSX, promoting cleaner and more semantically meaningful file naming in the codebase. -
It helps in preventing potential build or compile errors in advance. By enforcing a consistent file extension policy for JSX files, it ensures that build tools or compilers that expect JSX content to be in specific file types won’t encounter unexpected file extensions, thereby reducing the number of build-related issues caused by incorrect file extensions.
Enforce proper position of the first property in JSX
import React from 'react';
const MyComponent = () => (
<SomeComponent prop1="value1"
prop2="value2">
<ChildComponent />
</SomeComponent>
);
- This rule can improve code readability by consistently formatting the position of the first property in JSX tags, making the JSX structure easier to understand at a glance, especially for developers who are familiar with HTML but new to JSX.
- It helps to maintain a consistent code style across the project, or even across projects within the same organization, by enforcing a standard way of formatting JSX properties. This consistency is beneficial for team collaboration and code maintenance.
- By enforcing the first property to be on a new line for multiline JSX elements (depending on the configuration), it can make version control diffs cleaner and more focused. Changes to the opening tag or the first property are more clearly distinguished, simplifying code review and history exploration.
- The rule’s flexibility in configuration (‘multiline’, ‘multiline-multiprop’, ‘multiprop’, ‘always’, ‘never’) allows it to adapt to various coding styles and preferences. This tailored approach ensures that teams can enforce the rule in a way that aligns with their specific code style guidelines, enhancing developer satisfaction and adherence to coding standards.
Enforce shorthand or standard form for React fragments
import React from 'react';
function MyComponent() {
return (
<React.Fragment>
<div>Hello</div>
<div>World</div>
</React.Fragment>
);
}
- This rule enforces a consistent use of the shorthand or standard form for React fragments, which can lead to improved readability and conciseness in the code. By standardizing the syntax for fragments, it reduces the cognitive load for developers who are reading and writing React code.
- It includes a version check functionality to ensure that the shorthand syntax is only suggested if the React version in use supports it (React 16.2.0 and above). This is crucial for maintaining backward compatibility in projects that may not be updated to the latest version of React.
- The rule provides automatic fixable functionality that can transform long-form fragments (
<React.Fragment>...</React.Fragment>
) to the shorthand version (<>...</>
) or vice versa, depending on the configuration. This automated fixing helps in maintaining consistency with minimal manual effort. - It respects the developer’s choice or project’s configuration by allowing the enforcement of either shorthand or standard syntax based on the ESLint configuration. This flexibility ensures that teams can adopt the rule according to their coding standards and preferences, enhancing code style consistency across different projects.
Enforce event handler naming conventions in JSX
import React from 'react';
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
inputValue: '',
};
}
// Event handler not following naming conventions
changeInputValue = (event) => {
this.setState({ inputValue: event.target.value });
};
render() {
return (
<input
type="text"
value={this.state.inputValue}
onChange={this.changeInputValue} // Prop not following naming conventions
/>
);
}
}
- The rule enforces consistent naming for event handlers in JSX, which aids in making the code more readable and maintainable by clearly indicating functions that are used as event handlers. This consistency helps in quickly identifying event handler functions within components, making it easier for developers, especially those new to a codebase, to understand the component’s structure and logic.
- By requiring a specific prefix for event handler names (like ‘handle’ for the handlers themselves and ‘on’ for their props in JSX), it helps developers to immediately discern between event handler functions and other functions or methods that might not be directly tied to event handling, leading to less confusion and cleaner code organization.
- This rule also supports configuration for checking inline functions and local variables, offering flexibility in enforcing naming conventions based on team or project preferences. Such configuration can accommodate different coding practices, such as allowing inline functions for simple handlers while still maintaining overall naming consistency across the project.
- It prevents common mistakes and typos in naming event handlers and their corresponding props, especially in large and complex components. By programmatically enforcing naming conventions, it reduces the manual review efforts needed to catch these kinds of issues during code reviews, ultimately speeding up the development process and improving code quality.
Enforce props indentation in JSX
// Assuming the rule is configured for 2 spaces indentation
import React from 'react';
const MyComponent = () => (
<SomeComponent
firstProp="first"
secondProp="second"
thirdProp="third"
/>
);
- Ensures consistency in JSX prop indentation across the codebase, making the structure of components more predictable and easier for developers to read and understand.
- Allows flexibility in configuring indentation size (using spaces or tabs) and style (fixed indentation or aligned with the first prop), accommodating different project styles or developer preferences.
- Helps in identifying and automatically correcting irregular indentation, thereby reducing the time spent on manual code reviews and formatting concerning prop alignment in JSX.
- Supports ignoring indentation for ternary operators within props if specified, offering a tailored approach to linting that can adapt to specific coding practices or exceptions.
Enforce JSX indentation
class MyComponent extends React.Component {
render() {
return (<div>
<h1>Hello World</h1>
<p>This is a paragraph.</p>
</div>);
}
}
- The rule enforces a consistent indentation style for JSX elements, which improves readability and maintainability of the code by ensuring that elements and their children are clearly delineated. This is particularly important in complex component structures where nesting can become difficult to follow.
- It automatically fixes indentation inconsistencies, saving developers time during development and code review processes. This automation helps in maintaining code quality without manual intervention, making the codebase more approachable for new team members and reducing the likelihood of indentation-related bugs.
- The rule is configurable, allowing teams to specify their preferred indentation style (spaces or tabs) and size. This flexibility ensures that teams can adhere to their specific coding standards and practices without compromising on the benefits of consistent indentation.
- It covers various JSX scenarios including attributes, logical and conditional expressions, and nested elements, ensuring comprehensive enforcement of the indentation rule across all parts of a JSX structure. This thoroughness helps in catching and correcting indentation issues not only in the elements themselves but also in their attributes and expressions, leading to uniformly formatted code.
Disallow missing key
props in iterators/collection literals
const listItems = ['Item 1', 'Item 2', 'Item 3'].map((item) =>
<li>{item}</li>
);
-
This ESLint rule ensures that all elements created in an iterator (such as those generated by a
.map()
function) have akey
prop assigned. This is crucial for React’s rendering algorithm to accurately track changes in lists of elements, helping prevent unnecessary re-renders and potential bugs related to element identity. -
By checking for and enforcing the inclusion of a
key
prop in JSX elements and fragments generated in iterators, the rule aids in maintaining the performance optimization benefits that keys provide in React applications. Without keys, React cannot efficiently re-order elements in the DOM during updates, leading to degraded app performance. -
The rule optionally checks for the placement of the
key
prop in relation to spread attributes within JSX elements. This ensures that explicit key props are correctly recognized and not unintentionally overwritten by spread operations, which can be crucial for maintaining the intended behavior of component lists. -
It includes an option to warn about duplicate keys, which is vital because unique keys ensure that every element in a list can be distinctly identified from its siblings. Duplicate keys can lead to rendering issues, where React might incorrectly manage the elements during updates, causing unpredictable behavior in the user interface.
Enforce JSX maximum depth
// Assuming the max depth is set to 3
function BadComponent() {
return (
<div>
<section>
<article>
<header>
<nav>
{/* This exceeds the maximum depth of 3 */}
<a href="#">Link</a>
</nav>
</header>
</article>
</section>
</div>
);
}
-
This rule helps maintain readability and manageability of JSX code by enforcing a maximum depth. Deeply nested JSX can become difficult to read and maintain, much like deeply nested logic in regular programming. By limiting the depth, the code remains cleaner and more understandable.
-
By setting a limit on JSX nesting, this rule inadvertently encourages the practice of component decomposition. Developers are nudged towards breaking down complex components into smaller, reusable pieces, which is a key concept in React for creating maintainable and scalable applications.
-
Enforcing a maximum JSX depth can also improve performance in some cases. Deeply nested structures can lead to longer rendering times. By keeping the structure shallow, rendering becomes more efficient, as there are fewer components to traverse and render.
-
The rule also aids in identifying potential design flaws in the application. A need to nest components deeply might indicate that the UI is too complex or that the current component breakdown is not optimal. This can lead to early detection and correction of architectural issues, resulting in a better structured and more easily navigable codebase.
Enforce maximum of props on a single line in JSX
import React from 'react';
const UserProfile = () => {
return (
<div className="user-profile" id="user-1" userName="JohnDoe" age={30} location="USA" status="active">
John Doe's Profile
</div>
);
};
export default UserProfile;
- Enhances readability by ensuring that JSX components with multiple props do not become too cluttered on a single line, making it easier to identify, review, and understand each prop and its value.
- Improves code maintainability by enforcing a consistent structure for the placement of props across the codebase, thereby reducing the cognitive load when navigating through various components and their configurations.
- Aids in quicker code reviews and debugging by spacing out props onto separate lines (when exceeding the specified limit), which allows for easier pinpointing of typos, incorrect prop assignments, or missing props.
- Facilitates easier implementation of automated code formatting and styling tools, such as Prettier, by establishing a clear and enforceable guideline for how props should be structured, promoting a more uniform code appearance and minimizing merge conflicts related to code style preferences.
Require or prevent a new line after jsx elements and expressions.
function Greeting() {
return <div>Hello, world!</div><div>Welcome!</div>;
}
- The rule enforces a consistent formatting style by requiring or preventing a newline after JSX elements and expressions, which can make JSX code easier to read and maintain, particularly in large and complex components.
- It provides an option to allow multiline JSX elements and expressions to be exempt from the newline requirement, offering flexibility in applying the rule based on the specific needs of a project or component structure.
- By automatically fixing formatting inconsistencies, the rule can improve developer efficiency and reduce the time spent on manual code formatting, allowing developers to focus on more critical aspects of development.
- This rule can help prevent potential merge conflicts caused by inconsistent formatting styles among different developers working on the same codebase, thus facilitating smoother collaboration and code integration.
Disallow .bind()
or arrow functions in JSX props
class BadComponent extends React.Component {
constructor(props) {
super(props);
this.state = { message: "Hello" };
}
showMessage() {
alert(this.state.message);
}
render() {
return <button onClick={this.showMessage.bind(this)}>Show message</button>;
}
}
- This ESLint rule discourages the use of
.bind()
in JSX props which can help in avoiding unnecessary function re-creations during component re-render cycles. When a function is bound within a JSX prop, it gets re-created on every render, leading to performance degradation over time, especially in large and complex component trees. - It encourages the use of class properties initialized with arrow functions for event handlers or callbacks, which can lead to more consistent coding patterns within a project. This approach ensures that functions maintain the correct
this
context without needing to be bound in the render method or constructor, thereby promoting cleaner and more readable code. - By disallowing inline arrow functions in JSX props, this rule can also help in preventing subtle bugs related to the lexical scoping of
this
. Inline arrow functions create a new instance of the function each time the component re-renders, which could lead to unexpected behaviors in certain scenarios, especially when the functions are used as props for pure components or within shouldComponentUpdate lifecycle methods. - This rule accounts for various configurations and exceptions, such as allowing functions when they are necessary through configuration options. This flexibility enables teams to enforce the rule strictly in most cases while providing the necessary leeway for cases where functions in JSX props are justified, thus maintaining the balance between code quality and practical requirements.
Disallow comments from being inserted as text nodes
function CommentExample() {
return (
<div>
// This is an incorrect comment inside JSX text node
Here is some text.
{/* This is a correctly formatted comment */}
</div>
);
}
- Prevents the accidental inclusion of JavaScript style comments (
// comment
) within text nodes in JSX, which can lead to visual clutter in the rendered output or potentially expose comments to end-users that were intended to remain in the codebase. - Enforces the use of JSX comment syntax (
{/* comment */}
) for inserting comments within JSX elements, ensuring that the comments do not mistakenly become part of the UI displayed to the user. - Helps in maintaining consistency in how comments are written in JSX across the codebase, making it easier for developers to read and understand the code, especially for newcomers who might not be familiar with the nuances of commenting in JSX.
- Aids in the process of code review and debugging by clearly distinguishing between text meant to be rendered and comments meant for developers, thus preventing the misinterpretation of commented-out code or developer notes as actual UI text.
Disallows JSX context provider values from taking values that will cause needless rerenders
import React, { useState } from 'react';
const MyContext = React.createContext();
function App() {
const [count, setCount] = useState(0);
return (
<MyContext.Provider value={{ count, increment: () => setCount(count + 1) }}>
{/* Consumer components */}
</MyContext.Provider>
);
}
- Prevents unnecessary rerenders by stopping the JSX context provider’s value from being recreated on every render, which triggers the consumer components to rerender even if the actual context data hasn’t changed.
- Encourages the use of
useMemo
anduseCallback
hooks for optimizing context values, thereby promoting more efficient memory usage and preventing the creation of new functions and objects on each render. - Improves performance in React applications, especially those with deeply nested component trees or a large number of context consumers, by reducing the work React has to do in determining what needs to be updated.
- Enhances readability and maintainability by guiding developers to structure their context values more thoughtfully, making it easier to understand when and why context consumers should rerender.
Disallow duplicate properties in JSX
const MyComponent = () => {
return <div id="unique" id="duplicate" className="myClass"></div>;
};
- Ensures consistency and predictability in JSX properties by preventing the bug-prone scenario of declaring the same property multiple times, which can lead to unpredictable rendering outcomes and harder-to-debug components.
- By optionally allowing case-insensitive checks through the
ignoreCase
configuration, it provides flexibility in enforcing conventions in a codebase that might have varying case sensitivity practices, hence reducing potential for error due to oversight in case differences. - Improves code readability and maintainability by ensuring that each property is declared once, making the component’s interface with its props clear and unambiguous, thus aiding in understanding the component’s expected behavior without the confusion of duplicate declarations.
- Supports JSX spread attributes by skipping them during the check, thereby focusing on explicitly declared props. This approach ensures that the rule is compatible with dynamic prop spreading, a common pattern in React development, without falsely flagging these as duplicates, thus aligning with modern React development practices.
Disallow problematic leaked values from being rendered
function UserProfile({ user }) {
return (
<div>
{user && <h1>{user.name}</h1>}
{user.age && <p>Age: {user.age}</p>}
</div>
);
}
- This rule prevents the accidental rendering of falsey values (like
false
,null
,undefined
,0
,''
etc.) in JSX, which can lead to unexpected and often undesired visual outcomes in a React application. For instance, rendering0
or an empty string directly can be a common mistake when using logical operators for conditional rendering. - It promotes the use of explicit conditional expressions (
ternary operators
) over logical&&
operators for conditional rendering in JSX. This ensures that developers explicitly handle the cases where the condition fails, leading to clearer and more intentional render paths rather than relying on JavaScript’s coercion rules. - This rule encourages the enforcement of React version-specific best practices by incorporating version checks, such as the example that exempts empty strings from being flagged in React 18 and above. This awareness of framework versions helps maintain compatibility and leverages improvements or changes in behavior across different React versions.
- It facilitates automatic code fixes for identified issues, guiding developers towards adopting valid strategies for conditional rendering. By providing fix strategies, the rule not only highlights issues but actively aids in improving the code quality by suggesting more reliable patterns, encouraging developers to consider and handle potentially undefined or falsey cases explicitly.
Disallow usage of string literals in JSX
const HelloWorld = () => {
return <div>Hello, World!</div>;
};
- Encourages the extraction of strings into constants or localization files, making the codebase more maintainable and easier to internationalize. Having all strings in one place allows for simpler updates and translations without digging through the JSX code.
- Improves code readability and consistency by enforcing a uniform approach to handling strings within JSX. This results in a cleaner codebase where the intention of string usage is clear, whether it’s for UI elements, attributes, or dynamic content.
- Helps in preventing typographical or syntactical errors in string literals by promoting the use of variables. Variables can be checked, formatted, and validated in isolation, potentially reducing runtime errors related to incorrect string values.
- Facilitates better performance optimization practices. By discouraging inline string literals, this rule indirectly promotes the use of variables that can be efficiently managed and updated, leading to potentially fewer re-renders in a React application.
Disallow usage of javascript:
URLs
function BadLinkComponent() {
// Unsafe: Using `javascript:` URL
return <a href="javascript:alert('XSS Attack')">Click me</a>;
}
-
Prevents XSS Attacks: Using
javascript:
URLs can open up the application to cross-site scripting (XSS) attacks, where malicious scripts are executed in the context of the user’s browser. This rule helps in identifying such potentially dangerous URLs in JSX attributes and discouraging their use, thereby reducing the risk of XSS vulnerabilities. -
Encourages Safe Coding Practices: By disallowing
javascript:
URLs, this rule promotes safer and more secure coding practices among developers. It encourages the use of alternative methods for event handling or executing JavaScript code without embedding it directly in URLs, which is a more secure approach to web development. -
Improves Code Maintainability: Code that relies on
javascript:
URLs for functionality can be harder to debug and maintain, especially when such URLs are used as a workaround for implementing event handlers or other logic. This rule helps maintain a cleaner codebase by enforcing the use of proper event handling mechanisms provided by React, making the code easier to understand and maintain. -
Enhances Application Security: By disallowing the use of
javascript:
URLs, this rule indirectly contributes to the overall security posture of the application. It ensures that developers are not inadvertently introducing security flaws through the use of such URLs, which could be exploited by attackers to compromise the application or the data it handles.
Disallow target="_blank"
attribute without rel="noreferrer"
// Example of a React component with an external link missing rel="noreferrer"
function ExternalLink() {
return (
<a href="https://example.com" target="_blank">
Visit Example.com
</a>
);
}
- The rule specifically mitigates security risks associated with
target="_blank"
in anchor tags by ensuring thatrel="noreferrer"
is present. This prevents the new page from accessing the originating page’s window object, which can protect from certain types of phishing attacks or malicious scripts. - It enforces best practices for web development by automatically adding or suggesting the inclusion of
rel="noreferrer"
whentarget="_blank"
is used, promoting safer web development habits without developers needing to remember to add this attribute manually. - The rule is configurable to account for different development needs, such as allowing referrer information to be passed with
rel="noopener"
instead ofnoreferrer
if needed for analytics purposes, providing flexibility while still maintaining security. - It includes options to warn on spread attributes and dynamically enforce the rule on both links and forms, ensuring comprehensive coverage across different types of elements that can open new windows or submit data, thereby broadening the security measures applied throughout a web application.
Disallow undeclared variables in JSX
import React from 'react';
function MyComponent() {
return (
<div>
<SomeUndefinedComponent />
</div>
);
}
- Ensures that all JSX elements or components used within the code are defined or imported, helping to avoid runtime errors due to references to undefined components, which contributes to more stable and reliable applications.
- By detecting undeclared variables early in the development process, this rule aids in maintaining cleaner code and reduces the likelihood of bugs slipping through to production, leading to a smoother development workflow and a better end-user experience.
- The rule’s flexibility to ignore global variables if configured allows for tailored adherence to project-specific needs, ensuring that projects leveraging global components do not face unnecessary warnings, thus contributing to a more efficient coding environment.
- Provides an educative framework for developers, especially those new to React or JSX, helping them understand the importance of declaring components before use. This can accelerate the learning curve and improve coding standards across the team.
Disallow unnecessary fragments
function BadComponent() {
return (
<>
<div>Hello</div>
</>
);
}
- This rule helps in optimizing React component rendering by eliminating unnecessary JSX fragments, which can lead to slight performance improvements, especially in large applications where such patterns are recurring.
- Enforcing this rule can lead to a cleaner, more readable codebase by removing redundant syntax, making it easier for team members to understand and maintain the code.
- It can automatically fix instances of unnecessary fragments, thereby saving developer time and reducing the likelihood of introducing errors during manual cleanup.
- By disallowing unnecessary fragments, this rule ensures a more consistent code style across the project, making peer reviews more focused on logic rather than syntax preferences.
Require one JSX element per line
import React from 'react';
const HelloWorld = () => (
<div>Hello, <span>World</span>!</div>
);
- Enforces a consistent structure in JSX code by requiring that each JSX element or expression occupies its own line, which improves readability and maintainability, especially in complex components.
- Makes diffs cleaner and more intelligible. When elements or expressions are added or removed, the changes are isolated to specific lines, simplifying version control reviews.
- Helps to prevent common syntax errors that may arise from densely packed JSX expressions or elements, by imposing a structure that is easier to visually parse for correctness.
- Assists in visually distinguishing between elements and text nodes in JSX by separating them onto their own lines, making it clear when explicit spaces (
{' '}
) are required to maintain desired whitespace in the rendered output.
Enforce PascalCase for user-defined JSX components
function App() {
return (
<div>
<myComponent /> // Component name should be PascalCase
<another_component /> // Component name should be PascalCase
</div>
);
}
- Ensuring JSX components are named using PascalCase improves readability and consistency across the codebase, making it easier to distinguish between user-defined components and HTML tags.
- By allowing configuration options such as
allowAllCaps
,allowLeadingUnderscore
, andallowNamespace
, it provides flexibility to accommodate various coding styles and project-specific naming conventions without compromising the overall goal of maintaining a consistent naming scheme. - The rule’s ability to ignore specific names or patterns (using the
ignore
option) allows teams to progressively adopt this naming convention without having to refactor existing components immediately, thus providing a smoother transition path. - The detailed feedback provided when a name does not comply with the enforced PascalCase (or the allowed exceptions) helps developers quickly understand naming expectations and standards within their projects, reducing the time spent on code reviews and corrections related to component naming issues.
Disallow multiple spaces between inline JSX props
const myComponent = (
<MyComponent prop1="value1" prop2="value2" prop3="value3" />
);
-
Enforcing this rule ensures consistency in the spacing between inline JSX props across the codebase, which aids in maintaining a clean and organized code format. This consistency reduces cognitive load for developers when reading and writing components.
-
By disallowing multiple spaces between JSX props, the rule prevents potential readability issues that can arise from uneven or excessive spacing. This can be particularly beneficial for team members with visual impairments or those using screen readers, as consistent spacing improves the navigability of the code.
-
Automatically fixing spacing issues with this rule can significantly streamline the code review process. It eliminates the need for developers to manually check and correct spacing between props, allowing them to focus on more critical aspects of the code review, such as logic or architecture.
-
The rule’s ability to handle generic types within JSX attributes ensures that spacing checks are accurately applied even in complex components. This is particularly useful in TypeScript projects or any project utilizing JSX extensions, as it ensures that spacing consistency is maintained without breaking functionality.
Disallow JSX prop spreading
function BadComponent(props) {
return <AnotherComponent {...props} />;
}
-
Enhances code readability and maintainability: By disallowing JSX prop spreading, this rule ensures that developers explicitly list all props being passed to a component. This makes it easier to understand at a glance which props are being used, fostering a more maintainable and readable codebase.
-
Encourages better prop validation: With explicit prop declaration enforced by this rule, developers are more likely to define propTypes or TypeScript interfaces for their components. This leads to better type checking and validation, reducing the likelihood of runtime errors due to incorrect prop types.
-
Improves performance: Spreading props can lead to unnecessary re-renders since it creates a new object each time, potentially with more properties than needed. By specifying only the required props, components can avoid unnecessary updates, leading to optimized performance.
-
Enhances security: Prop spreading can inadvertently pass down props that were not intended to be received by a child component, including potentially sensitive data. By requiring explicit prop passing, this rule helps prevent such security vulnerabilities by ensuring only intended data is passed between components.
Enforce defaultProps declarations alphabetical sorting
class MyComponent extends React.Component {
// Other component details
}
MyComponent.defaultProps = {
zebra: false,
apple: true,
banana: true
};
-
Enhances Readability: Alphabetically sorting the
defaultProps
declarations makes it easier for developers to read and understand the default props being passed to a component. When props are organized, developers can quickly locate a specific prop without having to search through an unsorted list, improving code readability and maintainability. -
Consistency Across Codebase: Enforcing this sorting rule ensures that all
defaultProps
declarations follow a consistent order throughout the project. This uniformity helps in standardizing code practices across the codebase, making the code easier to follow for new developers or contributors. -
Prevents Merge Conflicts: In collaborative development environments, unsorted props can lead to unnecessary merge conflicts when different developers add new props independently. By keeping the
defaultProps
sorted, the likelihood of these conflicts is reduced as developers will be adding new props in a predetermined order. -
Automated Code Quality Improvement: This rule allows for automated enforcement and, where applicable, automatic fixing of the sorting order of
defaultProps
. This automation saves developers time during code reviews and manual testing by ensuring that the sorting order complies with the established coding standards, without requiring manual intervention.
Enforce props alphabetical sorting
<MyComponent name="John" age={30} ZipCode={10001} onEvent={handleEvent} />
- Improves readability and maintainability by enforcing a consistent ordering of props, making it easier to locate and manage them in large and complex components.
- Helps in minimizing merge conflicts in version control systems by having a universally agreed-upon order of properties, potentially reducing the time spent on resolving these conflicts.
- The rule’s configurable options such as
ignoreCase
,callbacksLast
,shorthandFirst/Last
, andmultiline
handling allow for flexibility in adopting the rule based on the team’s coding standards, accommodating varied preferences in prop ordering. - By providing immediate feedback through linting errors for props that are not in the desired order, it aids in adhering to best coding practices, leading to cleaner and more organized code bases.
Enforce spacing before closing bracket in JSX
// No space before the closing bracket in a self-closing JSX tag
import React from 'react';
function UserProfile() {
return (
<img src="userAvatar.png"/>
);
}
- Promotes a consistent code style within JSX by requiring or disallowing a space before the closing bracket of self-closing tags, making the code easier to read and maintain. It helps in distinguishing self-closing tags from opening tags at a glance, improving readability for developers familiar with HTML syntax.
- Helps prevent common coding style disagreements among team members or contributors by enforcing a project-specific rule, thereby reducing the number of stylistic changes during code reviews and allowing developers to focus on more critical aspects of code review.
- Automatically fixable, meaning that developers can save time and reduce manual efforts in formatting code according to this rule. Developers can rely on automated tools to apply this rule across the codebase consistently, ensuring that all JSX tags adhere to the specified style without manual intervention.
- Despite being deprecated in favor of
react/jsx-tag-spacing
, this rule provides precise control over spaces before the closing bracket of self-closing JSX tags. For projects not yet updated to use the recommended rule, it offers a way to maintain stylistic consistency and gradually transition to the newer rule without immediately overhauling existing code conventions.
Enforce whitespace in and around the JSX opening and closing brackets
import React from 'react';
class BadExample extends React.Component {
render() {
return <div><span/></div>;
}
}
- This rule enforces stylistic consistency by ensuring that whitespace in JSX opening and closing brackets follows a specific pattern, which can improve readability and maintainability of the code. It explicitly specifies how spaces should be used in and around the JSX opening and closing brackets, eliminating ambiguity and personal preference in code formatting.
- Enforcing this rule can help in avoiding syntax errors or unintended string concatenations in JSX. By ensuring that spaces are correctly placed around the opening and closing brackets of JSX tags, developers can avoid issues where tags are incorrectly interpreted as adjacent strings or adjacent to other tags, potentially leading to runtime errors or unexpected behaviors.
- The rule supports various configuration options to enforce different styles (e.g.,
afterOpening
,beforeSelfClosing
, etc.), allowing teams to adopt a style that best suits their project’s needs. This flexibility means teams can enforce a consistent style across their project while still adhering to their specific coding standards or preferences. - Applying such a rule in a codebase facilitates easier code review and collaboration among team members. Since the spacing around JSX tags is standardized, reviewers can focus more on the logic and performance implications of the code rather than discussing or correcting stylistic inconsistencies. This can lead to more productive code reviews and a smoother collaboration process within the team.
Disallow React to be incorrectly marked as unused
// Assuming React 16 or earlier without the new JSX transform
// This would trigger the react/jsx-uses-react rule because React is not used explicitly
import React from 'react';
function MyComponent() {
return <div>Hello</div>;
}
- This ESLint rule ensures that the React variable is recognized as “used” in files where JSX syntax is present. This is crucial for projects using versions of React prior to 17, where importing React in scope is necessary for the JSX to be transpiled correctly.
- It helps maintain consistency and clarity in projects that haven’t adopted the new JSX transform introduced in React 17, thereby assisting in avoiding potential errors that could arise from React being marked as unused by other linting rules or IDE features.
- By marking React and fragment variables as used when JSX elements or fragments are present in the code, it prevents potentially confusing and unnecessary edits where developers might remove the import statement for React, thinking it is unused, which would break the application.
- The rule specifically handles both regular JSX elements and fragment shorthand syntax, ensuring comprehensive coverage across different ways React might be utilized in JSX. This is particularly important for codebases that make heavy use of fragment syntax for returning multiple elements.
Disallow variables used in JSX to be incorrectly marked as unused
import React from 'react';
function UnusedComponent() {
// Incorrect: The variable `Header` is used in JSX below but will be reported as unused.
const Header = () => <h1>Hello, world!</h1>;
return (
<div>
Unused content that does not reference `Header`.
</div>
);
}
- This rule helps to identify JSX components that are defined but not used within the render method or return statement of a React component, reducing the risk of leaving unused variables in the codebase, which could lead to confusion and a cleaner code base.
- It aids in avoiding false positives by the linter where components are used in JSX but are incorrectly marked as unused by standard JavaScript analysis tools, ensuring a more accurate linting experience, especially beneficial in large and complex components where it’s easy to lose track of component usage.
- The rule improves code maintainability by encouraging the removal of unused variables or the correction of misspelled component names in JSX, leading to more efficient code that is easier to read and understand.
- By marking variables as used if they appear in JSX, it supports the use of higher-order components or dynamically generated components that might not be explicitly referenced in a way that static analysis could easily detect, thereby accommodating advanced React patterns and practices.
Disallow missing parentheses around multiline JSX
const MyComponent = () =>
<div>
<p>Hello, world!</p>
</div>;
- Enforcing the use of parentheses around multiline JSX helps to maintain consistency across the codebase, making it easier for developers to read and understand code by clearly distinguishing blocks of JSX from regular JavaScript code.
- This rule and its auto-fix functionality aid in preventing syntax errors that could occur from JavaScript’s automatic semicolon insertion (ASI) feature, which might incorrectly interpret the intention of the code when JSX elements are split across multiple lines without properly wrapped parentheses.
- By embedding logic to recognize and correct patterns both with and without new lines around the multiline JSX, this rule serves as an educational tool for developers, subtly guiding them towards best practices in JSX syntax directly within their development workflow.
- It supports various configuration options, allowing teams to adapt the rule to their specific coding style and guidelines. This flexibility ensures that the rule can be effectively integrated into diverse projects without forcing a one-size-fits-all approach, thereby respecting the unique needs and preferences of different development teams.
Disallow when this.state is accessed within setState
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0,
};
}
increment() {
// ❌ Bad: Using this.state directly inside setState
this.setState({
count: this.state.count + 1,
});
}
render() {
return (
<div>
<p>{this.state.count}</p>
<button onClick={() => this.increment()}>Increment</button>
</div>
);
}
}
-
Ensures synchronous state updates: Accessing
this.state
directly withinsetState
can lead to unpredictable state updates when there are multiplesetState
calls in a batch. This rule promotes using a function that receives the previous state, ensuring updates are applied synchronously and based on the most recent state. -
Prevents bugs due to state closure: Directly referencing
this.state
insidesetState
could cause closures over the state value at the time of an asynchronous operation’s initiation, rather than its execution, leading to potential bugs or outdated state references. The rule encourages a pattern that mitigates this risk. -
Enhances component performance: By avoiding direct access to
this.state
withinsetState
, it encourages the use of patterns like functional updates. This can lead to better performance in some scenarios by avoiding unnecessary re-renders or calculations based on stale state. -
Enforces best practices in state management within React components: This rule aligns with React’s recommendations for state management, especially in complex components where state updates depend on previous state values. It helps maintain readability and maintainability of the code by ensuring developers follow a standardized approach to state updates.
Disallow adjacent inline elements not separated by whitespace.
const Component = () => (
<div>
<span>Hello</span><a href="#">Click here</a>
</div>
);
- Improves readability of adjacent inline elements in the JSX structure, which is crucial for developers to easily distinguish between elements when quickly scanning through the code.
- Prevents potential layout issues in the user interface, where adjacent inline elements without space might unintentionally stick together, leading to an unexpected visual outcome.
- Encourages a best practice in the codebase by mandating explicit whitespace between inline elements, thereby standardizing how elements are spaced and ensuring consistency across different components.
- Aids in the detection and automatic correction of spacing issues during the development phase, significantly reducing manual review time and effort spent on identifying and fixing such UI layout concerns.
Disallow usage of Array index in keys
const todoItems = todos.map((todo, index) => (
<li key={index}>{todo.text}</li>
));
-
This ESLint rule,
react/no-array-index-key
, specifically discourages the use of array indices as keys in React elements, which is a significant practice to prevent potential issues with element reordering. Using indices as keys can lead to performance degradation and unexpected behavior in dynamic lists where the order of items might change, as React relies on keys to identify which items have changed, been added, or been removed. -
The rule is tailored to improve the stability of dynamic lists in React applications by enforcing the use of unique and consistent identifiers for list items as keys. This ensures that React can accurately and efficiently update the DOM in response to state changes, preventing unnecessary re-renders which can be triggered by using array indices as keys, especially after list modifications.
-
It automatically identifies patterns where developers commonly misuse array indices as keys within JSX and JavaScript expressions. For example, during mapping operations like
todos.map((todo, index) => <li key={index}>{todo.text}</li>);
which is highlighted as a bad practice. The rule provides a corrective suggestion to use unique identifiers (<li key={todo.id}>{todo.text}</li>
) instead, making it easier for developers to adhere to best practices without manually reviewing every list rendering operation. -
The rule supports a broad range of iterator functions beyond just
map
, includingevery
,filter
,find
,findIndex
,flatMap
,forEach
,reduce
,reduceRight
, andsome
, covering almost all use cases where developers might be tempted to use array indices as keys. This comprehensive approach ensures that the best practice is enforced consistently across different scenarios and code patterns, thereby maintaining the integrity and performance of React applications.
Lifecycle methods should be methods on the prototype, not class fields
import React, { Component } from 'react';
class MyComponent extends Component {
componentDidMount = () => {
// Lifecycle logic here
console.log('Component did mount!');
}
render() {
return (
<div>Hello, World!</div>
);
}
}
-
The rule enforces consistency across the codebase by ensuring all lifecycle methods are defined in the same way, improving readability and maintainability. By adhering to a traditional declaration, developers can more easily identify lifecycle methods at a glance.
-
It helps avoid potential issues with the
this
binding. Arrow functions lexically bindthis
, which might not always behave as expected within React lifecycle methods, especially if developers attempt to override them or use them in less conventional ways. -
Arrow functions as class properties (which is essentially what an incorrect lifecycle method declaration using arrow functions results in) are experimental syntax and not part of the ECMAScript standard yet. Using method declarations ensures compatibility and future-proofs the code.
-
By using proper method declarations for lifecycle methods, the code adheres more closely to the React documentation and community best practices. This reduces the learning curve for new developers and standardizes the approach to React component class construction, making code easier to understand and follow for developers familiar with React conventions.
Disallow passing of children as props
function MyComponent() {
return React.createElement('div', { children: 'Hello World' });
}
-
This rule helps ensure that children are passed to React components in the most idiomatic way, which is through JSX body content or the third argument in
React.createElement
, rather than as a direct prop. This aligns with React’s design philosophy and improves code readability, making it easier to understand the components’ structure at a glance. -
It encourages better composition practices by enforcing a clearer distinction between regular props and children. This distinction is crucial because children are often treated differently by components (for instance, by being rendered in a specific place within the component), and conflating them with props can lead to confusion and less maintainable code.
-
The rule can prevent potential bugs or unconventional behaviors in React components. Since passing children as a prop is not the standard pattern, it may not be handled correctly by all components, especially third-party ones that expect children to be passed in the conventional way. By enforcing the standard approach, the rule ensures greater compatibility and reliability of components within the React ecosystem.
-
It allows for exceptions when necessary by providing an option to allow functions as children props. This flexibility is important for cases where passing functions as children is a deliberate design choice (e.g., render props pattern) without entirely disabling the linting rule. This targeted approach ensures that the rule enhances code quality without being overly restrictive or hindering certain advanced patterns in React development.
Disallow when a DOM element is using both children and dangerouslySetInnerHTML
function MyComponent() {
return (
<div dangerouslySetInnerHTML={{ __html: "<span>Unsafe Content</span>" }}>
<p>This is a child element</p>
</div>
);
}
-
Prevents security risks by disallowing the combination of dangerouslySetInnerHTML with children in React components. This specific rule ensures that developers do not inadvertently create a vector for cross-site scripting (XSS) attacks by mixing both methods of setting inner content, which could lead to unescaped user input being rendered as HTML.
-
Promotes best practices in React development by enforcing a cleaner, more deliberate approach to component structure. By disallowing the use of dangerouslySetInnerHTML alongside children, this rule helps maintain the clarity of the component’s structure, making it easier for developers to understand and ensuring that only one method is used to define the content of a component.
-
Enhances code readability and maintainability by reducing complexity in the component’s definition. When developers are restricted from using dangerouslySetInnerHTML with children, it simplifies the decision-making process regarding how to inject content into the component, hence potentially leading to code that is easier to read and maintain over time.
-
Aids in automatic code analysis and safer code refactoring by providing a clear guideline on content injection within components. Automated tools can more easily detect violations of this rule, and developers can refactor code with confidence, knowing that they are adhering to recommended practices that avoid mixing potentially unsafe HTML content with standard child components.
Disallow usage of dangerous JSX properties
class MyComponent extends React.Component {
render() {
return <div dangerouslySetInnerHTML={{__html: this.props.content}} />;
}
}
- This rule helps in enforcing best security practices by disallowing the use of
dangerouslySetInnerHTML
, a known React property that can insert raw HTML into the DOM, potentially exposing the application to cross-site scripting (XSS) attacks if not properly sanitized. - By identifying and preventing the use of dangerous JSX properties like
dangerouslySetInnerHTML
, the rule encourages developers to find safer alternatives for inserting content into the DOM, such as directly using JSX or other React-safe methods. - The rule’s focus on specific dangerous properties ensures that developers are aware of the risks associated with certain practices in React, promoting a deeper understanding of React’s security model and how to maintain the safety of their applications.
- Implementing this rule as part of a project’s ESLint configuration can serve as an automated code review tool, catching instances of dangerous property usage before they are merged into production code, thus reducing the likelihood of introducing security vulnerabilities into a web application.
Disallow usage of deprecated methods
class MyComponent extends React.Component {
componentWillMount() {
// Initialization logic here is using deprecated lifecycle method
console.log('Component will mount!');
}
render() {
return <div>Hello, World!</div>;
}
}
- The rule specifically identifies and discourages the usage of deprecated React methods, encouraging developers to use current, recommended practices that align with the latest React API. This ensures codebases remain up-to-date and maintainable.
- By providing detailed information on deprecated methods, including the version they were deprecated in and suggesting alternatives, this rule serves as an educational tool. Developers not only know what not to use but also learn about the new methods intended to replace the deprecated ones.
- The rule’s integration with React’s versioning allows it to be contextually aware; it checks against the project’s React version to determine deprecation. This precision prevents false positives that could occur from a blanket ban on certain methods, acknowledging that certain projects might be locked to older versions of React for various reasons.
- It enhances code quality and future proofs projects by automatically identifying deprecated usage as part of the development process. This proactive approach reduces the technical debt associated with using outdated methods that may lose support or performance optimizations in future React versions, making the code more robust and easier to upgrade.
Disallow usage of setState in componentDidMount
class MyComponent extends React.Component {
componentDidMount() {
this.setState({
key: 'value',
});
}
render() {
// render logic
}
}
-
This rule helps ensure that React component state updates resulting from
setState
calls are not made immediately withincomponentDidMount
, which can lead to potential issues such as unnecessary re-renders or negatively impacting performance. Immediate state updates incomponentDidMount
can cause an additional rendering phase before the browser updates the screen, potentially leading to visible flickering or increased load times. -
Enforcing this rule can help developers follow recommended best practices in React, specifically avoiding direct state updates in lifecycle methods that are called immediately after a component is mounted. This can lead to a better structured and more predictable React component lifecycle management, which is crucial for maintaining large applications.
-
The rule makes an exception for setting state inside functions within
componentDidMount
, under certain configurations (allow-in-func
mode), allowing for more flexibility in cases where state updates need to be made after asynchronous operations (like data fetching) that are initiated incomponentDidMount
. This encourages developers to structure their code in a way that clearly separates immediate execution from asynchronous execution, improving code readability and maintainability. -
By disallowing the usage of
setState
directly incomponentDidMount
, it naturally steers developers towards using newer lifecycle methods or hooks (such ascomponentDidUpdate
, or theuseEffect
hook in functional components) for managing state updates in response to prop changes or as a result of asynchronous operations. This promotes the use of newer, more efficient practices in React development, contributing to overall application performance and maintainability.
Disallow usage of setState in componentDidUpdate
class MyComponent extends React.Component {
componentDidUpdate(prevProps) {
if (this.props.value !== prevProps.value) {
this.setState({value: this.props.value});
}
}
render() {
// Render logic here
}
}
-
Calling
setState
withincomponentDidUpdate
can lead to an infinite loop. SincecomponentDidUpdate
is called after the component updates andsetState
triggers an update, this rule helps prevent potential infinite rendering cycles that could arise from this pattern. -
Using this rule enforces a more predictable flow of state changes and updates in React components. By disallowing
setState
withincomponentDidUpdate
, developers are encouraged to find safer lifecycle methods or patterns for state updates, such asgetDerivedStateFromProps
, which is called before rendering. -
Following this ESLint rule helps in optimizing the performance of React applications. Infinite loops or excessive rendering caused by
setState
incomponentDidUpdate
can lead to sluggish performance and a poor user experience. This rule aids in preemptively addressing such performance issues. -
This ESLint rule encourages developers to rethink and refactor their component’s logic for state updates, promoting the use of more appropriate lifecycle methods or state management solutions. This leads to cleaner, more maintainable code that adheres to best practices in React development.
Disallow direct mutation of this.state
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
incrementCount() {
// Bad: Directly mutating state
this.state.count += 1;
}
render() {
return (
<div>
<button onClick={this.incrementCount.bind(this)}>Increment</button>
<p>{this.state.count}</p>
</div>
);
}
}
- This rule helps maintain React’s component immutability principle, making sure the state is treated as immutable. Direct state mutation can bypass React’s lifecycle methods, leading to a component that does not render or updates unpredictably.
- Enforcing the use of
setState()
for state updates, as recommended by this rule, ensures that the component gets properly re-rendered. When you mutate the state directly, React may not recognize the change, and thus the component might not re-render, leading to stale or incorrect UI. - By following this rule, developers are encouraged to use
setState()
in a functional form whenever the new state is derived from the previous state. This adherence promotes more predictable state transitions and safer asynchronous state updates. - Adherence to this rule enhances code readability and maintainability. It makes it clear where state updates occur and allows React to optimize performance through batching and efficient updates, which direct state mutation could compromise.
Disallow usage of findDOMNode
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
class MyComponent extends Component {
componentDidMount() {
const node = ReactDOM.findDOMNode(this);
console.log(node);
}
render() {
return <div>Hello World</div>;
}
}
- It prevents the use of
findDOMNode
, a method discouraged by React for being less efficient and more escape-hatch-like, which can lead to brittle code. React recommends using refs instead for directly accessing DOM elements, as illustrated in the rule’s fix example. - The rule aims to encourage more idiomatic React code practices by steering developers away from deprecated methods towards more React-friendly approaches like refs, resulting in code that is more maintainable and adheres to best practices recommended by the React team.
- By disallowing
findDOMNode
, this rule helps in preparing the codebase for future React updates and potential removal offindDOMNode
from the React API, thereby future-proofing the application and reducing the risk of encountering breaking changes in React upgrades. - The rule aids in improving performance. The direct manipulation of DOM nodes using
findDOMNode
can lead to suboptimal performance in React applications. By pushing towards ref usage, it ensures a more declarative way of accessing DOM elements that is better optimized by React, hence potentially enhancing the app’s performance.
Disallow usage of invalid attributes
import React from 'react';
const MyComponent = () => {
return (
<div class="myClass">Hello World</div>
);
};
export default MyComponent;
-
Prevents the use of invalid HTML attributes within JSX and React
createElement
calls, aiding in the development of valid HTML and improving compatibility across web browsers. For instance, enforcing the use ofclassName
overclass
in JSX to align with React’s naming conventions, as highlighted in the provided example. -
Enhances application accessibility by discouraging the use of attributes that are either deprecated or non-standard, which may not be consistently recognized by assistive technologies, leading to a more inclusive web experience.
-
Reduces potential runtime errors and debugging time by catching typos or incorrect attribute names early in the development process. This preemptive feedback loop can significantly improve developer productivity and code quality.
-
Promotes adherence to best practices and coding standards specific to React development by providing immediate feedback on attribute misuse within JSX code. This can also serve as an educational tool for developers learning React, familiarizing them with the correct usage of HTML attributes within React projects.
Disallow usage of isMounted
class MyComponent extends React.Component {
componentDidMount() {
setTimeout(() => {
if (this.isMounted()) { // Bad: using isMounted is considered an anti-pattern
this.setState({ someState: true });
}
}, 1000);
}
}
- This rule helps prevent the use of
isMounted
because using it can lead to memory leaks and performance issues. React does not clean up the component references after unmounting ifisMounted()
is used, which prevents the components from being garbage collected. - It encourages better lifecycle management practices. By manually tracking the mounted state of a component (
_isMounted
flag), developers are more aware of the lifecycle events and how they impact the component’s behavior, leading to more reliable and maintainable code. - The rule promotes the use of safer patterns for asynchronous operations. When relying on
isMounted
to check component’s mount state before callingsetState
, there’s a risk that the component gets unmounted before the asynchronous operation completes, potentially causing React to throw warnings or errors. Updating the state based on a manually managed flag (_isMounted
) mitigates this risk. - Emphasizing the manual tracking of the mounted state of a component instead of using
isMounted
follows React’s recommendations. React’s team has deprecatedisMounted
due to its issues and encourages developers to write components that can safely perform asynchronous operations without relying on such checks, leading to cleaner, safer code.
Disallow multiple component definition per file
import React from 'react';
class FirstComponent extends React.Component {
render() {
return <div>First Component</div>;
}
}
class SecondComponent extends React.Component {
render() {
return <div>Second Component</div>;
}
}
- It encourages better organization of code by ensuring that each React component lives in its own file, which can make it easier for developers to find, maintain, and test individual components.
- Helps in enforcing a modular architecture within a project, leading to more reusable and isolated components. This isolation improves the project’s scalability as components can be easily shared and updated across the project.
- It reduces complexity within files, making code review and debugging simpler. Developers can focus on understanding and refining one component at a time without being distracted by other components in the same file.
- By disallowing multiple component definitions per file, it can potentially lead to better performance in development tools (such as hot module reloading). Files are smaller, and changes to one component don’t require re-processing or re-compiling code related to other components in the same file.
Enforce that namespaces are not used in React elements
import React from 'react';
function MyComponent() {
return <custom:Component />;
}
- Prevents the usage of namespaces in React elements, which is not a standard JSX practice and could lead to confusion or compatibility issues with JSX parsers and tools. JSX expects components to be named with either PascalCase for user-defined components or lowercase for DOM tags, not with namespaces.
- Enhances code readability and maintainability by ensuring that React components follow the conventional naming schemes. This rule helps to keep the codebase consistent, making it easier for developers to understand and navigate the code.
- Helps in avoiding potential conflicts or errors that could arise from the misuse of namespaces in React elements. For instance, certain tooling or libraries might not support namespaced tags, leading to unexpected behavior or errors in the application.
- Facilitates better integration with the broader React ecosystem, including tooling, libraries, and community conventions. By adhering to widely accepted practices, projects are more likely to remain compatible with updates to these tools and practices over time.
Disallow usage of referential-type variables as default param in functional component
import React from 'react';
const UserProfile = ({ userInfo = { name: 'Guest', age: 30 } }) => (
<div>
<h1>Name: {userInfo.name}</h1>
<p>Age: {userInfo.age}</p>
</div>
);
- It prevents unintended sharing of mutable state across component instances, which can lead to bugs when one instance inadvertently modifies the state that other instances are using.
- Encourages the use of a factory function for default props that return referential types, which ensures that each component instance gets its own unique default prop value, safeguarding against unexpected mutations.
- Enhances component reusability and readability by clearly separating the default prop creation logic from the component function, making the component’s intent and behavior easier to understand.
- Helps in avoiding performance pitfalls associated with the creation of new objects in each re-render, by ensuring that referential equality is maintained between renders when the props are not passed, thus allowing React’s reconciliation process to work more efficiently.
Disallow usage of shouldComponentUpdate when extending React.PureComponent
class MyComponent extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
count: 0,
};
}
shouldComponentUpdate(nextProps, nextState) {
// A redundant check given PureComponent’s built-in shallow prop and state comparison,
// and might lead to bugs or performance issues.
return nextProps.count !== this.props.count || nextState.count !== this.state.count;
}
render() {
return <div>Count: {this.state.count}</div>;
}
}
- Ensures adherence to best practices: Implementing
shouldComponentUpdate
in components extendingReact.PureComponent
is redundant sincePureComponent
automatically implements a shallow props and state comparison. This rule helps maintain the intended efficiency gains of usingPureComponent
. - Prevents unnecessary re-renders: By discouraging the use of
shouldComponentUpdate
inPureComponent
, it prevents developers from inadvertently implementing deep comparison logic that could negate the performance benefits of shallow comparison, leading to unnecessary re-renders. - Reduces potential for bugs: Custom
shouldComponentUpdate
methods can introduce errors in update logic, especially when used inPureComponent
, where updates are expected to be managed automatically based on shallow prop and state comparison. This rule helps reduce the likelihood of such bugs. - Encourages proper usage of React’s component types: This ESLint rule guides developers to choose the right type of component based on their needs. If a developer finds themselves needing a
shouldComponentUpdate
method for optimization, it suggests they might actually need aReact.Component
instead of aReact.PureComponent
, thereby promoting a better understanding of React’s component model and its optimization mechanisms.
Disallow usage of the return value of ReactDOM.render
import React from 'react';
import ReactDOM from 'react-dom';
class MyApp extends React.Component {
render() {
return <div>Hello World</div>;
}
}
const appInstance = ReactDOM.render(<MyApp />, document.getElementById('app'));
- Prevents memory leaks and performance issues by discouraging the storage of the
ReactDOM.render
return value, which is contrary to the React paradigm of handling components. React’s component model is designed to be declarative and to manage the lifecycle and state of components internally, without requiring the user to interact with or store references to the rendered component instances. - Enforces best practices in React development, specifically for versions 15.0.0 and above, where the return value of
ReactDOM.render
changed from a reference to the component tovoid
. This rule ensures that developers do not rely on deprecated behavior that could break their applications in future React versions. - Encourages the use of ref callbacks or the newer
createRef
API for accessing DOM nodes or React elements, aligning with React’s focus on unidirectional data flow and component encapsulation. This improves code maintainability and readability, as it keeps the component interactions within the React ecosystem rather than relying on direct DOM manipulations or references. - Helps in maintaining consistency across a codebase by ensuring that all developers are following the same pattern when using
ReactDOM.render
. This consistency is crucial in larger projects where different developers might interact with DOM elements or React components, as it reduces the likelihood of bugs introduced by misunderstanding the return values of React’s rendering mechanism.
Disallow usage of setState
import React, { Component } from 'react';
class Counter extends Component {
constructor(props) {
super(props);
this.state = {
count: 0,
};
}
incrementCount = () => {
// This use of setState violates the react/no-set-state rule
this.setState({ count: this.state.count + 1 });
};
render() {
return (
<div>
<p>{this.state.count}</p>
<button onClick={this.incrementCount}>Increment</button>
</div>
);
}
}
export default Counter;
-
This rule encourages the adoption of functional components and React hooks over class components, aligning with modern React practices and promoting cleaner, more maintainable code structures. By discouraging
setState
, it nudges developers towards usinguseState
, which simplifies state management in functional components. -
It helps in preventing the common pitfalls associated with the asynchronous nature of
setState
in class components, such as state updates relying on the previous state not accounting for these updates being batched. Using hooks likeuseState
offers a more direct way to update state, potentially reducing bugs related to state management. -
Enforcing this rule can lead to improved performance of React applications. Functional components with hooks are generally lighter and faster than class components, partly because they avoid the overhead of class instances and make component re-rendering more efficient.
-
The rule supports better compatibility with future React updates and features. React’s development is increasingly focused on functional components and hooks. Adopting this style of components early on ensures easier upgrades and access to the latest React features and best practices.
Disallow using string references
class MyComponent extends React.Component {
componentDidMount() {
console.log(this.refs.myRef);
}
render() {
return <div ref="myRef">Hello, world!</div>;
}
}
-
The rule discourages the usage of string literals in refs, which are considered a legacy API in React. Using callback functions or the
createRef
API instead encourages a more modern, safer approach to React refs that is less prone to errors and more consistent with React’s current best practices. -
It ensures that components are more predictable and maintainable. String refs can lead to confusion and bugs, especially in larger applications where the scope and lifecycle of refs might not be clear. Callback refs, as encouraged by the fix, provide a clear and direct way to interact with DOM elements.
-
Enforcing this rule helps in the transition towards function components and hooks, as string refs are not supported in React’s function components. This makes codebases that adhere to this rule forward-compatible with the latest React features and patterns, such as hooks.
-
The rule aids in static analysis and optimization by React tools. Using callback refs or
React.createRef
gives React a clearer understanding of the ref’s usage, potentially allowing for more efficient rendering and updates. String refs, being more opaque, could hinder certain optimizations or static analysis efforts.
Disallow this
from being used in stateless functional components
const MyComponent = () => {
let someValue = this.state.someValue; // This is incorrect in an SFC because `this` is not defined
return <div>{someValue}</div>;
};
- This ESLint rule specifically helps ensure adherence to the functional component paradigm in React by preventing misuse of
this
in a scope where it is undefined, which is critical in avoiding runtime errors in Stateless Functional Components (SFCs). - By disallowing
this
in SFCs, the rule enforces the proper use of props and state passing mechanisms in functional components, which improves code readability and maintainability by making data flow more explicit and predictable. - It assists in optimizing performance, as functional components that correctly avoid using
this
aren’t concerned with the component context (this) bindings, potentially leading to less memory usage and faster execution times due to the optimal use of functional component characteristics. - The rule aids in the educational process for developers new to React or those transitioning from class components to functional components by highlighting a common mistake, thereby accelerating the learning curve and promoting best practices in React development.
Disallow common typos
import React from 'react';
import PropTypes from 'prop-types';
class MyComponent extends React.Component {
render() {
return <div>{this.props.title}</div>;
}
}
MyComponent.Proptypes = { // Typo here: Proptypes should be propTypes
title: PropTypes.string.isRequired,
};
export default MyComponent;
- Prevents common typing errors related to React component property type definitions, which can cause PropTypes to not validate prop types as expected, potentially leading to runtime bugs that are hard to diagnose.
- Ensures consistency across code base by enforcing the correct usage of
propTypes
property on React components, making it easier for new developers to follow best practices and established patterns without confusion. - Reduces the time spent debugging issues caused by typos in prop type definitions by catching these mistakes early in the development process, thereby improving development efficiency and reducing potential frustration.
- Enhances code readability and maintainability by ensuring property type definitions are correctly spelled and applied, helping developers quickly understand component prop requirements and expectations.
Disallow unescaped HTML entities from appearing in markup
function WelcomeMessage() {
return (
<div>
Welcome to my site! Please use the navigation bar on the <left> side.
</div>
);
}
-
This ESLint rule specifically targets unescaped HTML entities within JSX to ensure that they are properly encoded in the render output. Unescaped entities might be interpreted by the browser in unexpected ways, potentially leading to layout issues or exposing the application to cross-site scripting (XSS) attacks if dynamic content is improperly escaped.
-
It automatically detects these unescaped entities within the JSX code, aiming to reduce manual review effort and the risk of human error during development. By highlighting these issues in real-time, developers can promptly fix potential vulnerabilities and maintain code quality.
-
The rule offers a mechanism for specifying custom entities to forbid, beyond the default set, allowing projects to tailor the rule to their specific needs or coding standards. This customization enhances the rule’s applicability and effectiveness in maintaining a secure and consistent coding environment.
-
In the provided example of bad and fixed code, the rule not only identifies the issue but also suggests the correct way to escape the
<
character. This immediate feedback loop aids developers in learning and applying best practices for HTML entity handling in React applications, contributing to the overall robustness and security of the application.
Disallow usage of unknown DOM property
function MyComponent() {
return (
<div class="my-component">
Hello, world!
</div>
);
}
-
This rule helps in ensuring that developers do not mistakenly use HTML attributes with incorrect casing or names in JSX, such as using “class” instead of “className”. It directly relates to the example provided where
class
should be corrected toclassName
, highlighting a common mistake due to HTML and JSX syntax differences. -
It enhances code readability and maintainability by enforcing standardized attribute names. For instance, if a developer uses a non-standard or misspelled attribute, this rule will flag it. Consequently, teams are guided to use the correct and universally understood properties, which makes the codebase easier to understand and work with.
-
The rule assists in debugging and reducing runtime errors by catching potentially invalid DOM properties at compile time. For example, if a developer inadvertently uses an unknown property, this could lead to unexpected behavior in the user interface that might be hard to trace. By flagging these issues early, the rule helps in avoiding such pitfalls.
-
It offers automated fixes for common mistakes, particularly when a property name is close to a standard one but not exactly the same. This automation not only saves developer time but also ensures that the fixes are consistent across the codebase. For instance, if
autofocus
is incorrectly used instead of the standardautoFocus
in JSX, this rule can automatically suggest or apply the correct property name, thereby enhancing code quality with minimal manual intervention.
Disallow usage of unsafe lifecycle methods
class MyComponent extends React.Component {
UNSAFE_componentWillMount() {
// Initialization that could be done safely in `componentDidMount`
console.log('Component will mount');
}
UNSAFE_componentWillUpdate(nextProps, nextState) {
// Pre-update logic that could safely be moved to `componentDidUpdate`
console.log('Component will update');
}
UNSAFE_componentWillReceiveProps(nextProps) {
// Logic to handle new props, better suited for `static getDerivedStateFromProps`
console.log('Component will receive props');
}
render() {
return <div>Hello, World!</div>;
}
}
- Promotes the use of safe lifecycle methods recommended by React for versions 16.3.0 and above, ensuring that developers follow the best practices and guidelines provided by the React team for component lifecycle management.
- Helps to prevent potential bugs and issues arising from the use of deprecated lifecycle methods (e.g., UNSAFE_componentWillMount, UNSAFE_componentWillReceiveProps, and UNSAFE_componentWillUpdate) by enforcing the migration to safer alternatives like componentDidMount, getDerivedStateFromProps, and componentDidUpdate.
- Encourages the adoption of new and more performant lifecycle APIs that better support the asynchronous rendering capabilities introduced in React 16.3, hence optimizing application performance and user experience.
- Provides clear guidance and resources within the rule details to educate developers on the rationale behind moving away from unsafe methods, linking to official React documentation and articles that explain the improvements and the need for these changes, facilitating a smoother transition.
Disallow creating unstable components inside components
import React from 'react';
function MyComponent(props) {
// Nested component inside another component
const NestedComponent = () => <div>Nested component content</div>;
return (
<div>
<h1>Hello, world!</h1>
<NestedComponent />
</div>
);
}
- Enforces a best practice for performance optimization by preventing the re-creation of the nested component on every render of the parent component. This reduces unnecessary computations and re-renders, ultimately improving application performance.
- Promotes better component reusability across your application. By defining components outside of the parent component, you make it easier to reuse those nested components in other parts of your application without duplicating code.
- Increases the readability and maintainability of the code by keeping component definitions separate. This separation helps developers quickly understand the structure of components and their relationships without navigating through nested definitions.
- Helps in avoiding potential bugs related to the closure scope in JavaScript. Defining components inside other components can lead to unexpected behaviors regarding variables’ scope and lifecycles, which are more predictable when components are defined at the top level.
Disallow declaring unused methods of component class
import React, { Component } from 'react';
class MyComponent extends Component {
componentDidMount() {
console.log('Component did mount');
}
unusedMethod() {
console.log('This method is never used');
}
render() {
return <div>Hello, World!</div>;
}
}
export default MyComponent;
-
Improves Code Readability: Removing unused class component methods makes the codebase cleaner and more readable. By eliminating dead code, developers can more easily understand the component’s purpose and functionality, focusing on what’s actually being used and relevant.
-
Enhances Performance: While unused methods might not directly impact runtime performance significantly, their removal can contribute to a decrease in the overall bundle size, especially in large-scale applications. This can lead to faster load times and a more efficient application.
-
Facilitates Maintenance: By enforcing the removal of unused methods, this rule helps prevent the accumulation of outdated or obsolete code. This makes the component easier to maintain and refactor, as there’s less code to sift through when making changes or debugging.
-
Promotes Best Practices: This rule encourages developers to critically evaluate the necessity of each class component method they write. It prompts a mindset of writing purposeful code, aligning with best practices in software development where code is kept DRY (Don’t Repeat Yourself) and efficient.
Disallow definitions of unused propTypes
import PropTypes from 'prop-types';
import React from 'react';
class UserProfile extends React.Component {
render() {
return (
<div>
<p>Name: {this.props.name}</p>
</div>
);
}
}
UserProfile.propTypes = {
name: PropTypes.string.isRequired,
age: PropTypes.number // 'age' prop is defined but never used
};
- Prevents declaring
propTypes
that are never used in the component, which can lead to confusion and makes the code harder to maintain by leaving artifacts from past implementations or features that were considered but never actually used. - Helps in optimizing component’s performance slightly by reducing the overhead of validating unused prop types, especially in large-scale applications where every optimization counts.
- Encourages developers to keep the codebase clean and only include relevant and necessary code, which in turn improves readability and maintainability of the code. A lean codebase is easier to understand and manage, especially for new developers who are not familiar with the project.
- By identifying and removing unused
propTypes
, it helps in identifying potentially unused or unnecessary data passed to components, which might indicate overly complicated component interfaces or unused data fetching, thus potentially leading to simplification of component APIs or reducing unnecessary data fetching and state management complexity.
Disallow definitions of unused state
import React, { Component } from 'react';
class MyComponent extends Component {
constructor(props) {
super(props);
this.state = {
usedState: 1,
unusedState: 'This state is never used',
};
}
componentDidMount() {
console.log(this.state.usedState);
}
render() {
return <div>{this.state.usedState}</div>;
}
}
export default MyComponent;
- The
react/no-unused-state
rule efficiently identifies state properties in React components that are declared but never actually used in rendering or logic, helping developers to avoid keeping dead code in their codebase, which can lead to confusion and maintenance issues over time. - By automatically detecting unused state fields, it prompts developers to remove or refactor redundant state properties, leading to cleaner, more readable, and more performant React component code.
- This rule aids in the optimization of React components by ensuring that the component’s state is minimal and contains only the data it needs to function properly, which can indirectly improve the component’s performance by reducing unnecessary re-renders caused by state changes.
- It assists in enforcing best coding practices within a team or project by automatically enforcing a policy against unnecessary state properties, which can be particularly useful in larger projects where manual code reviews may not catch all instances of unused state, ensuring a higher code quality standard.
Disallow usage of setState in componentWillUpdate
class MyComponent extends React.Component {
componentWillUpdate(nextProps, nextState) {
if (nextProps.value !== this.props.value) {
this.setState({ value: nextProps.value }); // This is a bad practice
}
}
render() {
return <div>{this.state.value}</div>;
}
}
-
The rule specifically targets an outdated React lifecycle method,
componentWillUpdate
, advising against usingsetState
within it because doing so can lead to unexpected behavior in the component’s update lifecycle. This ensures components behave predictably when their state or props change. -
By disallowing
setState
incomponentWillUpdate
, the rule implicitly guides developers towards more appropriate lifecycle methods for state updates, such ascomponentDidUpdate
, which is the recommended method for responding to prop changes after a render has occurred. This promotes best practices within React development. -
The rule mitigates potential performance issues that can arise from setting state in
componentWillUpdate
, as it might lead to additional re-rendering cycles that are unnecessary or unintended. Preventing this practice helps in maintaining the application’s performance and responsiveness. -
It aids in future-proofing React applications by steering developers away from using
setState
in a lifecycle method that is considered unsafe and is deprecated in newer versions of React. This aligns with React’s move towards safer and more predictable update patterns, such as those encouraged by hooks and functional components.
Enforce ES5 or ES6 class for React Components
var React = require('react');
var MyComponent = React.createClass({
displayName: 'MyComponent',
getInitialState: function() {
return { count: 0 };
},
handleClick: function() {
this.setState({ count: this.state.count + 1 });
},
render: function() {
return React.createElement('button', { onClick: this.handleClick }, `Click count: ${this.state.count}`);
}
});
module.exports = MyComponent;
-
This ESLint rule enforces a consistent coding style for defining React components, specifically advocating for the use of ES6 classes over the
React.createClass
method when the configuration is set toalways
. This ensures that all components across a project adhere to the modern class syntax, promoting readability and maintainability. -
By encouraging the use of ES6 classes, the rule indirectly supports the use of the latest JavaScript features, such as class properties and inheritance. This can lead to more concise and expressive component definitions, as well as better alignment with the ongoing evolution of JavaScript and React itself.
-
The rule provides clear feedback when developers use a component definition style that does not match the project’s configured preference (ES5 with
React.createClass
vs. ES6 classes). This immediate feedback can help prevent the mixture of different component styles within a codebase, reducing the cognitive load on developers who need to understand or refactor the code. -
It facilitates an easier transition to future versions of React and JavaScript. As the language and library evolve, staying aligned with the recommended practices, such as using ES6 classes for React components, can simplify future migrations or adoption of new features. For instance, certain React features or optimizations may be available only or primarily to class components, and using ES6 classes ensures compatibility and access to these advancements.
Prefer exact proptype definitions
import PropTypes from 'prop-types';
import React from 'react';
const MyComponent = ({ name, age }) => (
<div>
<p>Name: {name}</p>
<p>Age: {age}</p>
</div>
);
MyComponent.propTypes = {
name: PropTypes.string,
age: PropTypes.number,
};
export default MyComponent;
- Promotes the definition of exact prop types in React components, ensuring that the component documentation is clear and that props passed are exactly as expected, preventing runtime errors associated with unexpected prop types.
- Helps in detecting prop types that may inadvertently be passed to a component, thereby reducing the potential for bugs that occur when an unexpected prop affects component behavior or overrides intended prop values.
- Encourages developers to explicitly declare all props as required or optional with detailed types, leading to more maintainable code by making prop expectations transparent and predictable.
- Enhances code readability and maintainability by enforcing a standardized approach to prop type definitions, making it easier for new developers to understand component interfaces and for teams to adhere to best practices in prop usage.
Enforce that props are read-only
interface UserProps {
name: string;
age: number;
}
const UserProfile: React.FC<UserProps> = (props) => {
// Someone might try to modify props, which is a bad practice
props.name = "New Name";
return (
<div>
<h1>{props.name}</h1>
<p>{props.age} years old</p>
</div>
);
};
- The rule enforces immutability for component props, which aligns with React’s recommendation to treat props as read-only. This prevents accidental modifications that could lead to unpredictable component behavior, enhancing the stability and predictability of components.
- By preventing modification of props, this rule aids in creating a more functional programming approach within React components. Immutable data is easier to track and debug because its state doesn’t change unexpectedly, making the application easier to understand and less prone to bugs related to state manipulation.
- The rule ensures that TypeScript compilation errors occur when attempting to modify props, serving as an immediate feedback mechanism for developers. This helps catch potential issues early in the development process, before they can manifest as runtime errors or bugs in the application’s UI.
- By advocating for props to be marked as
readonly
, the rule implicitly prompts developers to design components with clear input/output contracts. This fosters better component encapsulation and promotes the composition of components, as each component is less concerned with internal state changes of its children and more focused on how to compose them based on their props.
Enforce stateless components to be written as a pure function
import React, { Component } from 'react';
class Welcome extends Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
-
This ESLint rule enforces the use of functional components over class components when there is no state or lifecycle methods used within the component, promoting the adoption of React’s newer, more efficient functional component syntax. As of React 16.8 with the introduction of Hooks, functional components have become more versatile and are generally recommended for components that don’t need state or lifecycle methods.
-
By enforcing stateless components to be written as a pure function, this rule helps reduce the overall size of the codebase. Pure functions are typically shorter and more concise than class components, leading to code that is easier to read and maintain. The comparison between the ‘bad’ and ‘fix’ examples clearly shows how a class component can be converted into a more concise functional component, embodying this principle.
-
The rule aids in optimizing application performance. Stateless functional components, lacking a state and lifecycle methods, do not have to go through the component lifecycle that class components do, making them slightly more efficient in some cases. While modern React optimizations have lessened this gap, in large applications, favoring stateless functional components wherever possible can contribute to better performance.
-
It encourages the use of React’s built-in hooks API for managing side effects, state, and other React features in functional components. By discouraging the use of class components unless necessary, developers are nudged towards using hooks, which can lead to more consistent and modular code. This aligns with React’s direction towards functional components and hooks, as highlighted by the introduction of hooks in React 16.8, which provides functional components with capabilities previously only possible in class components.
Disallow missing props validation in a React component definition
import React from 'react';
const Greeting = (props) => {
return <h1>Hello, {props.name}!</h1>;
};
- Ensuring prop types are defined helps in maintaining type safety within React components, reducing runtime errors due to unexpected prop types, specifically in dynamically typed languages like JavaScript.
- It enforces documentation of component API expectations directly within the code, making it clearer for developers to understand what props a component expects, and with what type, increasing code readability and maintainability.
- By requiring explicit props validation, this rule aids in catching common bugs during development before they make it to production, leading to more robust and reliable code.
- Implementing this rule assists in standardizing component prop patterns across a project, leading to more consistent codebases where developers can easily navigate and understand each other’s components without diving deep into implementation details.
Disallow missing React when using JSX
// Bad: React is missing, but JSX syntax is used.
const MyComponent = () => {
return <div>Hello, world!</div>;
};
- This rule ensures that the React library is in scope where JSX syntax is used, which prevents runtime errors from occurring due to React not being defined. JSX elements transpile to
React.createElement
calls, and without React being imported, these calls will fail. - It promotes consistency in codebases where multiple developers might have different levels of understanding regarding the necessity of importing React in files where JSX is used. By enforcing the rule, it eliminates confusion and ensures that all JSX-containing files are handled in a uniform manner.
- By detecting the absence of React where JSX is utilized and providing a clear message on how to resolve the issue, it serves as an educational tool for developers, especially those who are new to React. This helps in faster onboarding and understanding of React’s requirements and best practices.
- It allows for a smoother upgrade path to newer versions of React that might automatically import React where JSX is used, such as with the new JSX Transform introduced in React 17. Ensuring React is in scope explicitly helps avoid reliance on this automatic transformation, making codebases more explicit and potentially easier to migrate or understand without relying on build-time transformations.
Enforce a defaultProps definition for every prop that is not a required prop
import PropTypes from 'prop-types';
function Greeting({ name }) {
return <h1>Hello, {name}</h1>;
}
Greeting.propTypes = {
name: PropTypes.string, // This prop is not marked as required and lacks defaultProps.
};
- Ensures that all non-required properties in React components have a defined default value, preventing potential bugs or undefined behavior at runtime when those props are not explicitly provided by the parent component.
- Improves code readability and maintainability by explicitly documenting the intended default behavior for properties, which can serve as a form of self-documentation for developers reviewing the codebase.
- Enhances component reusability by specifying defaultProps, allowing components to be used in various contexts without the need for providing all props, thereby making the components more flexible and easier to integrate.
- Aids in type safety by establishing default values for props, the rule helps in scenarios where strict type checking is enforced, reducing the likelihood of type-related runtime errors when the component is used in a TypeScript project or a project with PropTypes validation.
Enforce React components to have a shouldComponentUpdate method
import React, { Component } from 'react';
class MyComponent extends Component {
render() {
return (
<div>
<h1>Hello, World!</h1>
</div>
);
}
}
-
Encourages performance optimization: By ensuring that React components implement
shouldComponentUpdate
, developers are encouraged to consider when their components actually need to re-render. This can prevent unnecessary renders, improving the performance of React applications, especially in complex UIs or applications with frequent state updates. -
Promotes thoughtful development practices: The requirement to implement
shouldComponentUpdate
forces developers to think critically about their component’s dependencies and when updates should occur. This leads to more efficient and purposeful code, as developers must explicitly define the conditions under which a re-render is necessary, rather than relying on React’s default behavior. -
Increases awareness of component lifecycle: For developers, especially those new to React, having to implement
shouldComponentUpdate
introduces them to the component lifecycle method earlier. This awareness can lead to better debugging skills, as understanding when and why a component updates is crucial for diagnosing rendering issues and optimizing component performance. -
Ensures intentional UI updates: By defining specific criteria for when a component should update, it guarantees that UI changes are intentional and based on defined application state or prop changes. This reduces the risk of unintended renders that could lead to inconsistent UI behavior or display stale data, enhancing the user experience.
Enforce ES5 or ES6 class for returning value in render function
// Example of a class component in React not correctly implementing the render method
import React, { Component } from 'react';
class MyComponent extends Component {
render() {
<div>Hello, World!</div> // This line is missing the return statement
}
}
- Ensures consistency in the syntax and structure within React class components, making the code easier to read and understand for all team members by enforcing the presence of a return statement in the render method.
- Helps in early detection of bugs related to missing return statements in render methods, which can prevent the component from rendering correctly and lead to hours of debugging.
- Improves maintainability and scalability of the codebase by setting a clear standard for how render methods should be written, thereby reducing potential technical debt caused by inconsistent coding practices.
- Enhances learning and adherence to best practices for new team members or contributors who are unfamiliar with the necessity of returning a value in the render method of class components in React, thus promoting better coding habits.
Disallow extra closing tags for components without children
import React from 'react';
function App() {
return (
<div>
<Header></Header>
<main>
{/* Some content */}
</main>
<Footer></Footer>
</div>
);
}
export default App;
- Using the
react/self-closing-comp
ESLint rule enforces cleaner and more concise code by eliminating unnecessary closing tags for components that don’t contain children. This leads to easier-to-read and more maintainable code, specifically improving the readability of JSX structures in React applications. - The rule specifically takes into account both custom React components and DOM elements, ensuring a consistent code style across different types of components. This distinction is important because it ensures that the linting rule is applicable in a variety of use cases within React projects, addressing both HTML elements and custom component implementations.
- It provides automatic fix capabilities, which can save developers a significant amount of time by automatically converting components to their self-closing form when applicable. This feature is particularly useful for large codebases, where manually finding and updating each instance could be cumbersome and error-prone.
- The rule also intelligently handles white space within components, allowing for components that contain only multiline spaces (potentially for formatting purposes) to be considered as having no children. This nuanced approach prevents unnecessary linting errors in scenarios where whitespace is intentionally used for readability or code organization, while still enforcing the self-closing tag rule when the component effectively has no children.
Enforce component methods order
class MyComponent extends React.Component {
// Event handler method is placed before lifecycle methods
onClick = () => {
console.log('Clicked');
}
// React lifecycle method
componentDidMount() {
console.log('Component did mount');
}
constructor(props) {
super(props);
this.state = { clicked: false };
}
render() {
return <button onClick={this.onClick}>Click me</button>;
}
}
- Enforcing a consistent method order in React components increases code readability and maintainability, especially for new developers unfamiliar with the component or the project.
- Since lifecycle methods are critical for understanding how a component interacts with the rest of the application (e.g., initialization, mounting, updating, unmounting), having them placed consistently makes it quicker to grasp the component’s behavior.
- Placing event handlers and other custom methods after the lifecycle methods but before the render method helps in identifying which parts of the component are React specific and which are custom logic added by the developers.
- Organized structure following this rule can aid in debugging by making it easier to navigate through the component’s methods, as developers can intuitively know where to locate lifecycle methods, event handlers, and the render method without having to search through unorganized code.
Enforce defaultProps declarations alphabetical sorting
class MyComponent extends React.Component {
// unsorted defaultProps
static defaultProps = {
zebra: false,
apple: true,
carrot: 'yes',
};
}
- Ensures consistency in the ordering of
defaultProps
, making it easier for developers to locate and read prop definitions by adhering to a predictable structure. This is particularly beneficial in components with a large number of props. - Reduces the potential for merge conflicts in version-controlled projects. Alphabetically sorted properties are less likely to cause conflicts when different developers add new props independently.
- Improves maintainability and readability of code by enforcing a standardized order, which can be particularly helpful for new team members getting acquainted with the codebase.
- Facilitates better code reviews by streamlining the process of checking
defaultProps
declarations, as reviewers can quickly verify the order without having to search through unsorted object properties.
Enforce propTypes declarations alphabetical sorting
import PropTypes from 'prop-types';
class MyComponent extends React.Component {
static propTypes = {
zebra: PropTypes.string,
alpha: PropTypes.bool.isRequired,
elephant: PropTypes.number,
beta: PropTypes.func,
};
}
-
The rule enforces propTypes to be declared in alphabetical order, which improves readability and maintainability of the code by ensuring that the properties are easy to locate and compare. This saves time when developers are looking for specific properties or assessing the overall structure.
-
It supports configurations like
requiredFirst
,callbacksLast
, andignoreCase
, allowing for more nuanced and flexible sorting that can align with a team’s or project’s specific coding standards. This adaptability ensures that the sorting logic can cater to different preferences and requirements, such as prioritizing required properties or grouping callback functions. -
By providing a fixer function, it not only identifies issues but also offers automatic corrections, streamlining the development process and reducing manual effort for developers. This helps in maintaining consistency across the codebase without requiring developers to sort the properties manually, thereby reducing human error.
-
The rule accounts for variations in prop declaration styles (such as spread elements, and referencing propTypes from external sources) and supports sorting within complex propTypes (like shapes). This comprehensive approach ensures that the sorting logic is consistently applied in various scenarios, reducing the likelihood of overlooked discrepancies and fostering uniformity throughout the project’s propTypes declarations.
Enforce class component state initialization style
class MyComponent extends React.Component {
state = { counter: 0 };
constructor(props) {
super(props);
}
render() {
return <div>{this.state.counter}</div>;
}
}
-
The rule enforces a consistent style for state initialization in React class components, ensuring that all developers in a team initialize component state following the same pattern, either inside the constructor or as a class property. This consistency makes the codebase easier to understand and maintain.
-
By specifying when and how state should be initialized (
always
in the constructor vs.never
as a class property), the rule can help prevent potential issues related to the timing of state initialization. In some cases, initializing state outside of the constructor might lead to unexpected behaviors, especially when the state depends on props or needs to be set based on some conditions that are only available in the constructor. -
Adhering to this ESLint rule can help new developers or contributors to a project quickly understand the expected practices and patterns for state initialization in class components, enhancing the learning curve and helping them write code that aligns with the project’s standards right from the start.
-
The rule assists in making the codebase more uniform and predictable, which is particularly beneficial during code reviews and refactoring. When state initialization follows a standard practice, reviewers can focus more on the logic and less on the style preferences, leading to more efficient code reviews and reducing the likelihood of introducing bugs during refactoring.
Enforces where React component static properties should be positioned.
class MyComponent extends React.Component {
static propTypes = {
name: PropTypes.string
};
constructor(props) {
super(props);
this.state = { count: 0 };
}
static defaultProps = {
name: 'John Doe'
};
render() {
return <div>Hello, {this.props.name}</div>;
}
}
-
This rule promotes consistency in codebase by ensuring that all React component static properties, like
propTypes
anddefaultProps
, are positioned in the same manner across multiple components. This makes the code easier to read and maintain, especially in larger projects where consistency in code structure is crucial for efficient teamwork. -
By enforcing a specific position for static properties, it potentially increases code readability and organization. Developers can quickly identify component props and their defaults without having to look inside the component class, making the codebase more navigable.
-
It helps prevent errors related to the misuse or incorrect placement of React component static properties. Since the rule enforces a specific structure, it reduces the likelihood that a developer will place these properties inconsistently, which could lead to hard-to-debug issues in the component’s behavior.
-
Adhering to this rule can lead to better optimization of transpilation and bundling processes. For instance, some configurations or tools might optimize static property assignments outside of class declarations more effectively than inline static properties. This can contribute to slight improvements in performance and bundle size in large-scale applications.
Enforce style prop value is an object
import React from 'react';
const MyComponent = () => {
return (
<div style="color: red;">This text should be red.</div>
);
}
- Ensures consistency in defining styles for React components by enforcing the use of object literals for the
style
prop, making it easier to read and maintain styles across the project. - Helps in preventing potential bugs and confusing behaviors by disallowing the use of non-object literals like strings or numbers for styling, which React does not support and could lead to runtime errors if misused.
- Encourages developers to adopt inline styling practices that leverage JavaScript objects, facilitating dynamic styling scenarios where styles can be programmatically altered.
- Enhances code understandability and maintenance by providing clear rules around styling practices, ensuring that new contributors and team members adhere to established project standards when using the
style
prop in JSX elements.
Disallow void DOM elements (e.g. <img />
, <br />
) from receiving children
import React from 'react';
function BadComponent() {
// This is bad because a <br /> element, being a void element, should not contain children.
return <br>Should not have children</br>;
}
- Ensures consistency and correctness in how void DOM elements are used, specifically preventing them from having children, which aligns with the HTML specification that these elements cannot contain content.
- Helps in preventing runtime errors or unexpected behavior in React applications by enforcing the restriction at the linting stage, potentially saving debugging time.
- Improves code readability and maintenance by signifying which elements are self-closing and should not be expected to wrap child elements, making the structure of the code clearer.
- Encourages best practices in React development by ensuring developers use the correct form of void elements, like
<img />
and<br />
, which enhances code quality and adheres to web standards.