# Eslint Plugin React > --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/boolean-prop-naming.md # Enforces consistent naming for boolean props (`react/boolean-prop-naming`) Allows you to enforce a consistent naming pattern for props which expect a boolean value. > **Note**: You can provide types in runtime types using [PropTypes] and/or statically using [TypeScript] or [Flow]. This rule will validate your prop types regardless of how you define them. ## Rule Details Examples of **incorrect** code for this rule: ```jsx var Hello = createReactClass({ propTypes: { enabled: PropTypes.bool }, render: function() { return
; }; }); ``` ```jsx type Props = { enabled: boolean } const Hello = (props: Props) =>
; ``` Examples of **correct** code for this rule: ```jsx var Hello = createReactClass({ propTypes: { isEnabled: PropTypes.bool }, render: function() { return
; }; }); ``` ```jsx type Props = { isEnabled: boolean } const Hello = (props: Props) =>
``` ## Rule Options ```js ... "react/boolean-prop-naming": [, { "propTypeNames": Array, "rule": , "message": , "validateNested": }] ... ``` ### `propTypeNames` The list of prop type names that are considered to be booleans. By default this is set to `['bool']` but you can include other custom types like so: ```jsx "react/boolean-prop-naming": ["error", { "propTypeNames": ["bool", "mutuallyExclusiveTrueProps"] }] ``` ### `rule` The RegExp pattern to use when validating the name of the prop. The default value for this option is set to: `"^(is|has)[A-Z]([A-Za-z0-9]?)+"` to enforce `is` and `has` prefixes. For supporting "is" and "has" naming (default): - isEnabled - isAFK - hasCondition - hasLOL ```jsx "react/boolean-prop-naming": ["error", { "rule": "^(is|has)[A-Z]([A-Za-z0-9]?)+" }] ``` For supporting "is" naming: - isEnabled - isAFK ```jsx "react/boolean-prop-naming": ["error", { "rule": "^is[A-Z]([A-Za-z0-9]?)+" }] ``` ### `message` The custom message to display upon failure to match the rule. This overrides the default message. If you choose to use a custom message, you have access to two template variables. - `propName` – the name of the prop that does not match the pattern - `pattern` – the pattern against which all prop names are tested For example, if a prop is named `something`, and if the rule's pattern is set to `"^(is|has)[A-Z]([A-Za-z0-9]?)+"`, you could set the custom message as follows: ```js message: 'It is better if your prop ({{ propName }}) matches this pattern: ({{ pattern }})' ``` And the failure would look like so: ```plaintext It is better if your prop (something) matches this pattern: (^is[A-Z]([A-Za-z0-9]?)+) ``` ### `validateNested` This value is boolean. It tells if nested props should be validated as well. By default this is set to false but you can change it to true, to validate deeper layers of object: ```jsx "react/boolean-prop-naming": ["error", { "validateNested": true }] ``` [PropTypes]: https://reactjs.org/docs/typechecking-with-proptypes.html [TypeScript]: https://www.typescriptlang.org/ [Flow]: https://flow.org/ --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/button-has-type.md # Disallow usage of `button` elements without an explicit `type` attribute (`react/button-has-type`) The default value of the `type` attribute for HTML `button` elements is `"submit"`. This is often not the desired behavior and may lead to unexpected page reloads. This rules enforces an explicit `type` attribute for all `button` elements and checks that its value is valid per the spec (i.e., is one of `"button"`, `"submit"`, and `"reset"`). ## Rule Details Examples of **incorrect** code for this rule: ```jsx var Hello = var Hello = var Hello = var Hello = React.createElement('button', {}, 'Hello') var Hello = React.createElement('button', {type: 'foo'}, 'Hello') ``` Examples of **correct** code for this rule: ```jsx var Hello = Hello var Hello = Hello var Hello = var Hello = var Hello = var Hello = var Hello = React.createElement('span', {}, 'Hello') var Hello = React.createElement('span', {type: 'foo'}, 'Hello') var Hello = React.createElement('button', {type: 'button'}, 'Hello') var Hello = React.createElement('button', {type: 'submit'}, 'Hello') var Hello = React.createElement('button', {type: 'reset'}, 'Hello') var Hello = React.createElement('button', {type: condition ? 'button' : 'submit'}, 'Hello') ``` ## Rule Options ```js ... "react/button-has-type": [, { "button": , "submit": , "reset": }] ... ``` You can forbid particular type attribute values by passing `false` as corresponding option (by default all of them are `true`). Examples of **incorrect** code for this rule, when configured with `{ "reset": false }`: ```jsx var Hello = var Hello = var Hello = React.createElement('button', {type: 'reset'}, 'Hello') var Hello = React.createElement('button', {type: condition ? "button" : "reset"}, 'Hello') ``` ## When Not To Use It If you use only `"submit"` buttons, you can disable this rule --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/checked-requires-onchange-or-readonly.md # Enforce using `onChange` or `readonly` attribute when `checked` is used (`react/checked-requires-onchange-or-readonly`) This rule enforces `onChange` or `readonly` attribute for `checked` property of input elements. It also warns when `checked` and `defaultChecked` properties are used together. ## Rule Details Example of **incorrect** code for this rule: ```jsx React.createElement('input', { checked: false }); React.createElement('input', { type: 'checkbox', checked: true }); React.createElement('input', { type: 'checkbox', checked: true, defaultChecked: true }); ``` Example of **correct** code for this rule: ```jsx {}} /> React.createElement('input', { type: 'checkbox', checked: true, onChange() {} }); React.createElement('input', { type: 'checkbox', checked: true, readOnly: true }); React.createElement('input', { type: 'checkbox', checked: true, onChange() {}, readOnly: true }); React.createElement('input', { type: 'checkbox', defaultChecked: true }); ``` ## Rule Options ```js "react/checked-requires-onchange-or-readonly": [, { "ignoreMissingProperties": , "ignoreExclusiveCheckedAttribute": }] ``` --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/default-props-match-prop-types.md # Enforce all defaultProps have a corresponding non-required PropType (`react/default-props-match-prop-types`) This rule aims to ensure that any prop in `defaultProps` has a non-required type definition. > **Note**: You can provide types in runtime types using [PropTypes] and/or statically using [TypeScript] or [Flow]. This rule will validate your prop types regardless of how you define them. Having `defaultProps` for non-existent prop types is likely the result of errors in refactoring or a sign of a missing prop type. Having a `defaultProp` for a required property similarly indicates a possible refactoring problem. ## Rule Details Examples of **incorrect** code for this rule: ```jsx function MyStatelessComponent({ foo, bar }) { return
{foo}{bar}
; } MyStatelessComponent.propTypes = { foo: React.PropTypes.string.isRequired, bar: React.PropTypes.string }; MyStatelessComponent.defaultProps = { foo: "foo" }; ``` ```jsx var Greeting = React.createClass({ render: function() { return
Hello {this.props.foo} {this.props.bar}
; }, propTypes: { foo: React.PropTypes.string, bar: React.PropTypes.string }, getDefaultProps: function() { return { baz: "baz" }; } }); ``` ```jsx class Greeting extends React.Component { render() { return (

Hello, {this.props.foo} {this.props.bar}

); } } Greeting.propTypes = { foo: React.PropTypes.string.isRequired, bar: React.PropTypes.string }; Greeting.defaultProps = { foo: "foo" }; ``` ```jsx class Greeting extends React.Component { render() { return (

Hello, {this.props.foo} {this.props.bar}

); } static propTypes = { foo: React.PropTypes.string, bar: React.PropTypes.string.isRequired }; static defaultProps = { baz: "baz" }; } ``` ```jsx type Props = { foo: string, bar?: string }; function MyStatelessComponent(props: Props) { return
Hello {props.foo} {props.bar}
; } MyStatelessComponent.defaultProps = { foo: "foo", bar: "bar" } ``` Examples of **correct** code for this rule: ```jsx function MyStatelessComponent({ foo, bar }) { return
{foo}{bar}
; } MyStatelessComponent.propTypes = { foo: React.PropTypes.string, bar: React.PropTypes.string.isRequired }; ``` ```jsx function MyStatelessComponent({ foo, bar }) { return
{foo}{bar}
; } MyStatelessComponent.propTypes = { foo: React.PropTypes.string.isRequired, bar: React.PropTypes.string }; MyStatelessComponent.defaultProps = { bar: 'some default' }; ``` ```jsx type Props = { foo: string, bar?: string }; function MyStatelessComponent(props: Props) { return
Hello {props.foo} {props.bar}
; } MyStatelessComponent.defaultProps = { bar: 'some default' }; ``` ```js function NotAComponent({ foo, bar }) {} NotAComponent.propTypes = { foo: React.PropTypes.string, bar: React.PropTypes.string.isRequired }; ``` ## Rule Options ```js ... "react/default-props-match-prop-types": [, { "allowRequiredDefaults": }] ... ``` ### `allowRequiredDefaults` When `true` the rule will ignore `defaultProps` for required prop types. Examples of **correct** code for this rule, when configured with `{ "allowRequiredDefaults": true }`: ```jsx function MyStatelessComponent({ foo, bar }) { return
{foo}{bar}
; } MyStatelessComponent.propTypes = { foo: React.PropTypes.string.isRequired, bar: React.PropTypes.string }; MyStatelessComponent.defaultProps = { foo: "foo" }; ``` ## When Not To Use It If you don't care about stray `defaultsProps` in your components, you can disable this rule. ## Related rules - [require-default-props](./require-default-props.md) ## Resources - [Official React documentation on defaultProps](https://legacy.reactjs.org/docs/typechecking-with-proptypes.html#default-prop-values) [PropTypes]: https://reactjs.org/docs/typechecking-with-proptypes.html [TypeScript]: https://www.typescriptlang.org/ [Flow]: https://flow.org/ --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/destructuring-assignment.md # Enforce consistent usage of destructuring assignment of props, state, and context (`react/destructuring-assignment`) πŸ”§ This rule is automatically fixable by the [`--fix` CLI option](https://eslint.org/docs/latest/user-guide/command-line-interface#--fix). Rule can be set to either of `always` or `never`; ```js "react/destructuring-assignment": [, 'always'] ``` ## Rule Details By default rule is set to `always` enforce destructuring assignment. Examples of **incorrect** code for this rule: ```js const MyComponent = (props) => { return (
) }; ``` ```js const Foo = class extends React.PureComponent { render() { return
{this.context.foo}
; } }; ``` Below pattern is correct: ```js const MyComponent = ({id}) => { return (
) }; ``` ```js const MyComponent = (props, context) => { const { id } = props; return (
) }; ``` ```js const Foo = class extends React.PureComponent { render() { const { title } = this.context; return
{title}
; } }; ``` Examples of **incorrect** code for this rule, when configured with `"never"`: ```js const MyComponent = ({id}) => { return (
) }; ``` ```js const MyComponent = (props) => { const { id } = props; return (
) }; ``` ```js const Foo = class extends React.PureComponent { render() { const { title } = this.state; return
{title}
; } }; ``` and below pattern is correct: ```js const MyComponent = (props) => { return (
) }; ``` ```js const Foo = class extends React.PureComponent { render() { return
{this.state.title}
; } }; ``` ## Rule Options ```js ... "react/destructuring-assignment": [, "always", { "ignoreClassFields": , "destructureInSignature": "always" | "ignore" }] ... ``` ### `ignoreClassFields` When configured with `true`, the rule will ignore class field declarations. Examples of **correct** code for this rule: ```jsx class Foo extends React.PureComponent { bar = this.props.bar } ``` ### `destructureInSignature` (default: "ignore") This option can be one of `always` or `ignore`. When configured with `always`, the rule will require props destructuring happens in the function signature. Examples of **incorrect** code for `destructureInSignature: 'always'` : ```jsx function Foo(props) { const {a} = props; return <>{a} } ``` Examples of **correct** code for `destructureInSignature: 'always'` : ```jsx function Foo({a}) { return <>{a} } ``` ```jsx // Ignores when props is used elsewhere function Foo(props) { const {a} = props; useProps(props); // NOTE: it is a bad practice to pass the props object anywhere else! return } ``` --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/display-name.md # Disallow missing displayName in a React component definition (`react/display-name`) πŸ’Ό This rule is enabled in the β˜‘οΈ `recommended` [config](https://github.com/jsx-eslint/eslint-plugin-react/#shareable-configs). DisplayName allows you to name your component. This name is used by React in debugging messages. ## Rule Details Examples of **incorrect** code for this rule: ```jsx var Hello = createReactClass({ render: function() { return
Hello {this.props.name}
; } }); const Hello = React.memo(({ a }) => { return <>{a} }) export default ({ a }) => { return <>{a} } ``` Examples of **correct** code for this rule: ```jsx var Hello = createReactClass({ displayName: 'Hello', render: function() { return
Hello {this.props.name}
; } }); const Hello = React.memo(function Hello({ a }) { return <>{a} }) ``` ## Rule Options ```js ... "react/display-name": [, { "ignoreTranspilerName": , "checkContextObjects": }] ... ``` ### `ignoreTranspilerName` (default: `false`) When `true` the rule will ignore the name set by the transpiler and require a `displayName` property in this case. Examples of **correct** code for `{ ignoreTranspilerName: true }` option: ```jsx var Hello = createReactClass({ displayName: 'Hello', render: function() { return
Hello {this.props.name}
; } }); module.exports = Hello; ``` ```jsx export default class Hello extends React.Component { render() { return
Hello {this.props.name}
; } } Hello.displayName = 'Hello'; ``` ```jsx export default function Hello({ name }) { return
Hello {name}
; } Hello.displayName = 'Hello'; ``` Examples of **incorrect** code for `{ ignoreTranspilerName: true }` option: ```jsx var Hello = createReactClass({ render: function() { return
Hello {this.props.name}
; } }); module.exports = Hello; ``` ```jsx export default class Hello extends React.Component { render() { return
Hello {this.props.name}
; } } ``` ```jsx module.exports = createReactClass({ render: function() { return
Hello {this.props.name}
; } }); ``` ```jsx export default class extends React.Component { render() { return
Hello {this.props.name}
; } } ``` ```jsx function HelloComponent() { return createReactClass({ render: function() { return
Hello {this.props.name}
; } }); } module.exports = HelloComponent(); ``` ### checkContextObjects (default: `false`) `displayName` allows you to [name your context](https://reactjs.org/docs/context.html#contextdisplayname) object. This name is used in the React dev tools for the context's `Provider` and `Consumer`. When `true` this rule will warn on context objects without a `displayName`. Examples of **incorrect** code for this rule: ```jsx const Hello = React.createContext(); ``` ```jsx const Hello = createContext(); ``` Examples of **correct** code for this rule: ```jsx const Hello = React.createContext(); Hello.displayName = "HelloContext"; ``` ```jsx const Hello = createContext(); Hello.displayName = "HelloContext"; ``` ## About component detection For this rule to work we need to detect React components, this could be very hard since components could be declared in a lot of ways. For now we should detect components created with: - `createReactClass()` - an ES6 class that inherit from `React.Component` or `Component` - a stateless function that return JSX or the result of a `React.createElement` call. --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/forbid-component-props.md # Disallow certain props on components (`react/forbid-component-props`) By default this rule prevents passing of [props that add lots of complexity](https://medium.com/brigade-engineering/don-t-pass-css-classes-between-components-e9f7ab192785) (`className`, `style`) to Components. This rule only applies to Components (e.g. ``) and not DOM nodes (e.g. `
`). The list of forbidden props can be customized with the `forbid` option. ## Rule Details This rule checks all JSX elements and verifies that no forbidden props are used on Components. This rule is off by default. Examples of **incorrect** code for this rule: ```jsx ``` ```jsx ``` Examples of **correct** code for this rule: ```jsx ``` ```jsx
``` ```jsx
``` ## Rule Options ```js ... "react/forbid-component-props": [, { "forbid": [|] }] ... ``` ### `forbid` An array specifying the names of props that are forbidden. The default value of this option is `['className', 'style']`. Each array element can either be a string with the property name or object specifying the property name or glob string, an optional custom message, and a component allowlist: ```js { "propName": "someProp", "allowedFor": ["SomeComponent", "AnotherComponent"], "message": "Avoid using someProp except SomeComponent and AnotherComponent" } ``` Use `disallowedFor` as an exclusion list to warn on props for specific components. `disallowedFor` must have at least one item. ```js { "propName": "someProp", "disallowedFor": ["SomeComponent", "AnotherComponent"], "message": "Avoid using someProp for SomeComponent and AnotherComponent" } ``` For `propNamePattern` glob string patterns: ```js { "propNamePattern": '**-**', "allowedFor": ['div'], "message": "Avoid using kebab-case except div" } ``` ```js { "propNamePattern": '**-**', "allowedForPatterns": ["*Component"], "message": "Avoid using kebab-case except components that match the `*Component` pattern" } ``` Use `allowedForPatterns` for glob string patterns: ```js { "propName": "someProp", "allowedForPatterns": ["*Component"], "message": "Avoid using `someProp` except components that match the `*Component` pattern" } ``` Use `disallowedForPatterns` for glob string patterns: ```js { "propName": "someProp", "disallowedForPatterns": ["*Component"], "message": "Avoid using `someProp` for components that match the `*Component` pattern" } ``` Combine several properties to cover more cases: ```js { "propName": "someProp", "allowedFor": ['div'], "allowedForPatterns": ["*Component"], "message": "Avoid using `someProp` except `div` and components that match the `*Component` pattern" } ``` ### Related rules - [forbid-dom-props](./forbid-dom-props.md) --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/forbid-dom-props.md # Disallow certain props on DOM Nodes (`react/forbid-dom-props`) This rule prevents passing of props to elements. This rule only applies to DOM Nodes (e.g. `
`) and not Components (e.g. ``). The list of forbidden props can be customized with the `forbid` option. ## Rule Details This rule checks all JSX elements and verifies that no forbidden props are used on DOM Nodes. This rule is off by default. Examples of **incorrect** code for this rule: ```jsx // [1, { "forbid": ["id"] }]
``` ```jsx // [1, { "forbid": ["style"] }]
``` Examples of **correct** code for this rule: ```jsx // [1, { "forbid": ["id"] }] ``` ```jsx // [1, { "forbid": ["id"] }] ``` ## Rule Options ```js ... "react/forbid-dom-props": [, { "forbid": [|] }] ... ``` ### `forbid` An array of strings, with the names of props that are forbidden. The default value of this option `[]`. Each array element can either be a string with the property name or object specifying the property name, an optional custom message, and a DOM nodes disallowed list (e.g. `
`): ```js { "propName": "someProp", "disallowedFor": ["DOMNode", "AnotherDOMNode"], "message": "Avoid using someProp" } ``` ### Related rules - [forbid-component-props](./forbid-component-props.md) --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/forbid-elements.md # Disallow certain elements (`react/forbid-elements`) You may want to forbid usage of certain elements in favor of others, (e.g. forbid all `
` and use `` instead). This rule allows you to configure a list of forbidden elements and to specify their desired replacements. ## Rule Details This rule checks all JSX elements and `React.createElement` calls and verifies that no forbidden elements are used. This rule is off by default. If on, no elements are forbidden by default. ## Rule Options ```js ... "react/forbid-elements": [, { "forbid": [] }] ... ``` ### `forbid` An array of strings and/or objects. An object in this array may have the following properties: - `element` (required): the name of the forbidden element (e.g. `'button'`, `'Modal'`) - `message`: additional message that gets reported A string item in the array is a shorthand for `{ element: string }`. Examples of **correct** code for this rule: ```jsx // [1, { "forbid": ["button"] }]
React.createElement('div', {}, React.createElement('button', {}, React.createElement('input'))); ``` ## When Not To Use It If you don't want to forbid any elements. --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/forbid-foreign-prop-types.md # Disallow using another component's propTypes (`react/forbid-foreign-prop-types`) This rule forbids using another component's prop types unless they are explicitly imported/exported. This allows people who want to use [babel-plugin-transform-react-remove-prop-types](https://github.com/oliviertassinari/babel-plugin-transform-react-remove-prop-types) to remove propTypes from their components in production builds, to do so safely. In order to ensure that imports are explicitly exported it is recommended to use the ["named" rule in eslint-plugin-import](https://github.com/benmosher/eslint-plugin-import/blob/HEAD/docs/rules/named.md) in conjunction with this rule. ## Rule Details This rule checks all objects and ensures that the `propTypes` property is not used. Examples of **incorrect** code for this rule: ```js import SomeComponent from './SomeComponent'; SomeComponent.propTypes; var { propTypes } = SomeComponent; SomeComponent['propTypes']; ``` Examples of **correct** code for this rule: ```js import SomeComponent, {propTypes as someComponentPropTypes} from './SomeComponent'; ``` ## Rule Options ```js ... "react/forbid-foreign-prop-types": [, { "allowInPropTypes": [] }] ... ``` ### `allowInPropTypes` If `true`, the rule will not warn on foreign propTypes usage inside a propTypes declaration. ## When Not To Use It This rule aims to make a certain production optimization, removing prop types, less prone to error. This rule may not be relevant to you if you do not wish to make use of this optimization. If you are writing a higher-order component that hoists the wrapped component's propTypes, you might want to disable this rule. --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/forbid-prop-types.md # Disallow certain propTypes (`react/forbid-prop-types`) By default this rule prevents vague prop types with more specific alternatives available (`any`, `array`, `object`), but any prop type can be disabled if desired. The defaults are chosen because they have obvious replacements. `any` should be replaced with, well, anything. `array` and `object` can be replaced with `arrayOf` and `shape`, respectively. ## Rule Details This rule checks all JSX components and verifies that no forbidden propsTypes are used. This rule is off by default. Examples of **incorrect** code for this rule: ```jsx var Component = createReactClass({ propTypes: { a: PropTypes.any, r: PropTypes.array, o: PropTypes.object }, ... }); class Component extends React.Component { ... } Component.propTypes = { a: PropTypes.any, r: PropTypes.array, o: PropTypes.object }; class Component extends React.Component { static propTypes = { a: PropTypes.any, r: PropTypes.array, o: PropTypes.object } render() { return
; } } ``` ## Rule Options ```js ... "react/forbid-prop-types": [, { "forbid": [], "checkContextTypes": , "checkChildContextTypes": }] ... ``` ### `forbid` An array of strings, with the names of `PropTypes` keys that are forbidden. The default value for this option is `['any', 'array', 'object']`. ### `checkContextTypes` Whether or not to check `contextTypes` for forbidden prop types. The default value is `false`. ### `checkChildContextTypes` Whether or not to check `childContextTypes` for forbidden prop types. The default value is `false`. ## When Not To Use It This rule is a formatting/documenting preference and not following it won't negatively affect the quality of your code. This rule encourages prop types that more specifically document their usage. --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/forward-ref-uses-ref.md # Require all forwardRef components include a ref parameter (`react/forward-ref-uses-ref`) πŸ’‘ This rule is manually fixable by [editor suggestions](https://eslint.org/docs/latest/use/core-concepts#rule-suggestions). Requires that components wrapped with `forwardRef` must have a `ref` parameter. Omitting the `ref` argument is usually a bug, and components not using `ref` don't need to be wrapped by `forwardRef`. See ## Rule Details This rule checks all React components using `forwardRef` and verifies that there is a second parameter. The following patterns are considered warnings: ```jsx var React = require('react'); var Component = React.forwardRef((props) => (
)); ``` The following patterns are **not** considered warnings: ```jsx var React = require('react'); var Component = React.forwardRef((props, ref) => (
)); var Component = React.forwardRef((props, ref) => (
)); function Component(props) { return
; }; ``` ## When not to use If you don't want to enforce that components using `forwardRef` utilize the forwarded ref. --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/function-component-definition.md # Enforce a specific function type for function components (`react/function-component-definition`) πŸ”§ This rule is automatically fixable by the [`--fix` CLI option](https://eslint.org/docs/latest/user-guide/command-line-interface#--fix). This option enforces a specific function type for function components. ## Rule Details This rule is aimed to enforce consistent function types for function components. By default it prefers function declarations for named components and function expressions for unnamed components. Examples of **incorrect** code for this rule: ```jsx // function expression for named component const Component = function (props) { return
{props.content}
; }; // arrow function for named component const Component = (props) => { return
{props.content}
; }; // arrow function for unnamed component function getComponent() { return (props) => { return
{props.content}
; }; } ``` ## Rule Options This rule takes an options object as a second parameter where the preferred function type for components can be specified. The first property of the options object is `"namedComponents"` which can be `"function-declaration"`, `"function-expression"`, `"arrow-function"`, or an array containing any of those, and has `'function-declaration'` as its default. The second property is `"unnamedComponents"` that can be either `"function-expression"`, `"arrow-function"`, or an array containing any of those, and has `'function-expression'` as its default. ```js ... "react/function-component-definition": [, { "namedComponents": "function-declaration" | "function-expression" | "arrow-function" | Array<"function-declaration" | "function-expression" | "arrow-function">, "unnamedComponents": "function-expression" | "arrow-function" | Array<"function-expression" | "arrow-function"> }] ... ``` Examples of **incorrect** code for this rule: ```jsx // only function declarations for named components // [2, { "namedComponents": "function-declaration" }] const Component = function (props) { return
; }; const Component = (props) => { return
; }; // only function expressions for named components // [2, { "namedComponents": "function-expression" }] function Component (props) { return
; }; const Component = (props) => { return
; }; // only arrow functions for named components // [2, { "namedComponents": "arrow-function" }] function Component (props) { return
; }; const Component = function (props) { return
; }; // only function expressions for unnamed components // [2, { "unnamedComponents": "function-expression" }] function getComponent () { return (props) => { return
; }; } // only arrow functions for unnamed components // [2, { "unnamedComponents": "arrow-function" }] function getComponent () { return function (props) { return
; }; } ``` Examples of **correct** code for this rule: ```jsx // only function declarations for named components // [2, { "namedComponents": "function-declaration" }] function Component (props) { return
; } // only function expressions for named components // [2, { "namedComponents": "function-expression" }] const Component = function (props) { return
; }; // only arrow functions for named components // [2, { "namedComponents": "arrow-function" }] const Component = (props) => { return
; }; // only function expressions for unnamed components // [2, { "unnamedComponents": "function-expression" }] function getComponent () { return function (props) { return
; }; } // only arrow functions for unnamed components // [2, { "unnamedComponents": "arrow-function" }] function getComponent () { return (props) => { return
; }; } ``` ## Unfixable patterns There is one unfixable pattern in JavaScript. It has to do with the fact that this is valid syntax: ```js export default function getComponent () { return
; } ``` While these are not: ```js export default var getComponent = () => { return
; } export default var getComponent = function () { return
; } ``` These patterns have to be manually fixed. ## Heads up, TypeScript users Note that the autofixer is somewhat constrained for TypeScript users. The following patterns can **not** be autofixed in TypeScript: ```tsx // function expressions and arrow functions that have type annotations cannot be autofixed to function declarations // [2, { "namedComponents": "function-declaration" }] const Component: React.FC = function (props) { return
; }; const Component: React.FC = (props) => { return
; }; // function components with one unconstrained type parameter cannot be autofixed to arrow functions because the syntax conflicts with jsx // [2, { "namedComponents": "arrow-function" }] function Component(props: Props) { return
; }; const Component = function (props: Props) { return
; }; // [2, { "unnamedComponents": "arrow-function" }] function getComponent() { return function (props: Props) => { return
; } } ``` Type parameters do not produce syntax conflicts if either there are multiple type parameters or, if there is only one constrained type parameter. The following patterns can be autofixed in TypeScript: ```tsx // autofix to function expression with type annotation // [2, { "namedComponents": "function-expression" }] const Component: React.FC = (props) => { return
; }; // autofix to arrow function with type annotation // [2, { "namedComponents": "function-expression" }] const Component: React.FC = function (props) { return
; }; // autofix to named arrow function with one constrained type parameter // [2, { "namedComponents": "arrow-function" }] function Component(props: Props) { return
; } const Component = function (props: Props) { return
; }; // autofix to named arrow function with multiple type parameters // [2, { "namedComponents": "arrow-function" }] function Component(props: Props) { return
; } const Component = function (props: Props) { return
; }; // autofix to unnamed arrow function with one constrained type parameter // [2, { "unnamedComponents": "arrow-function" }] function getComponent() { return function (props: Props) => { return
; }; } // autofix to unnamed arrow function with multiple type parameters // [2, { "unnamedComponents": "arrow-function" }] function getComponent() { return function (props: Props) => { return
; } } ``` ## When Not To Use It If you are not interested in consistent types of function components. --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/hook-use-state.md # Ensure destructuring and symmetric naming of useState hook value and setter variables (`react/hook-use-state`) πŸ’‘ This rule is manually fixable by [editor suggestions](https://eslint.org/docs/latest/use/core-concepts#rule-suggestions). πŸ’‘ This rule provides editor [suggestions](https://eslint.org/docs/developer-guide/working-with-rules#providing-suggestions). ## Rule Details This rule checks whether the value and setter variables destructured from a `React.useState()` call are named symmetrically. Examples of **incorrect** code for this rule: ```js import React from 'react'; export default function useColor() { // useState call is not destructured into value + setter pair const useStateResult = React.useState(); return useStateResult; } ``` ```js import React from 'react'; export default function useColor() { // useState call is destructured into value + setter pair, but identifier // names do not follow the [thing, setThing] naming convention const [color, updateColor] = React.useState(); return [color, updateColor]; } ``` Examples of **correct** code for this rule: ```js import React from 'react'; export default function useColor() { // useState call is destructured into value + setter pair whose identifiers // follow the [thing, setThing] naming convention const [color, setColor] = React.useState(); return [color, setColor]; } ``` ```js import React from 'react'; export default function useColor() { // useState result is directly returned return React.useState(); } ``` ## Rule Options ```js ... "react/hook-use-state": [, { "allowDestructuredState": }] ... ``` ### `allowDestructuredState` When `true` the rule will ignore the name of the destructured value. Examples of **correct** code for this rule, when configured with `{ "allowDestructuredState": true }`: ```jsx import React from 'react'; const [{foo, bar, baz}, setFooBarBaz] = React.useState({foo: "bbb", bar: "aaa", baz: "qqq"}) ``` --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/iframe-missing-sandbox.md # Enforce sandbox attribute on iframe elements (`react/iframe-missing-sandbox`) The sandbox attribute enables an extra set of restrictions for the content in the iframe. Using sandbox attribute is considered a good security practice. See ## Rule Details This rule checks all React iframe elements and verifies that there is sandbox attribute and that it's value is valid. In addition to that it also reports cases where attribute contains `allow-scripts` and `allow-same-origin` at the same time as this combination allows the embedded document to remove the sandbox attribute and bypass the restrictions. The following patterns are considered warnings: ```jsx var React = require('react'); var Frame = () => (
{React.createElement('iframe')}
); ``` The following patterns are **not** considered warnings: ```jsx var React = require('react'); var Frame = {React.createElement('iframe', { sandbox: "allow-popups" })}
); ``` ## When not to use If you don't want to enforce sandbox attribute on iframe elements. --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-boolean-value.md # Enforce boolean attributes notation in JSX (`react/jsx-boolean-value`) πŸ”§ This rule is automatically fixable by the [`--fix` CLI option](https://eslint.org/docs/latest/user-guide/command-line-interface#--fix). When using a [boolean attribute in JSX](https://web.archive.org/web/20160607204033/http://facebook.github.io/react/docs/jsx-in-depth.html#boolean-attributes), you can set the attribute value to `true` or omit the value. ## Rule Details This rule will enforce one or the other to keep consistency in your code. ## Rule Options This rule takes two arguments. If the first argument is `"always"` then it warns whenever an attribute is missing its value. If `"never"` then it warns if an attribute has a `true` value. The default value of this option is `"never"`. The second argument is optional. If provided, it must be an object. These properties are supported: First, the `"never"` and `"always"` properties are one set. The two properties cannot be set together. `"never"` must be used when the first argument is `"always"` and `"always"` must be used when the first argument is `"never"`. This property’s value must be an array of strings representing prop names. When the first argument is `"never"`, a boolean `"assumeUndefinedIsFalse"` may be provided, which defaults to `false`. When `true`, an absent boolean prop will be treated as if it were explicitly set to `false`. Examples of **incorrect** code for this rule, when configured with `"never"`, or with `"always", { "never": ["personal"] }`: ```jsx var Hello = ; ``` Examples of **correct** code for this rule, when configured with `"never"`, or with `"always", { "never": ["personal"] }`: ```jsx var Hello = ; ``` Examples of **incorrect** code for this rule, when configured with `"always"`, or with `"never", { "always": ["personal"] }`: ```jsx var Hello = ; ``` Examples of **correct** code for this rule, when configured with `"always"`, or with `"never", { "always": ["personal"] }`: ```jsx var Hello = ; ``` Examples of **incorrect** code for this rule, when configured with `"never", { "assumeUndefinedIsFalse": true }`, or with `"always", { "never": ["personal"], "assumeUndefinedIsFalse": true }`: ```jsx var Hello = ; ``` Examples of **correct** code for this rule, when configured with `"never", { "assumeUndefinedIsFalse": true }`, or with `"always", { "never": ["personal"], "assumeUndefinedIsFalse": true }`: ```jsx var Hello = ; ``` ## When Not To Use It If you do not want to enforce any style for boolean attributes, then you can disable this rule. --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-child-element-spacing.md # Enforce or disallow spaces inside of curly braces in JSX attributes and expressions (`react/jsx-child-element-spacing`) ## Rule Details Since React removes extraneous new lines between elements when possible, it is possible to end up with inline elements that are not rendered with spaces between them and adjacent text. This is often indicative of an error, so this rule attempts to detect JSX markup with ambiguous spacing. Examples of **incorrect** code for this rule: ```jsx
Here is a link
``` ```jsx
This text is bold
``` Examples of **correct** code for this rule: ```jsx
Spacing is {' '} explicit
``` ```jsx
Lack of spacing is{/* */}explicit
``` ## When Not To Use It You can turn this rule off if you are not concerned with inline elements appearing adjacent to text, or if you always explicitly include `{' '}` between elements to denote spacing. --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-closing-bracket-location.md # Enforce closing bracket location in JSX (`react/jsx-closing-bracket-location`) πŸ”§ This rule is automatically fixable by the [`--fix` CLI option](https://eslint.org/docs/latest/user-guide/command-line-interface#--fix). Enforce the closing bracket location for JSX multiline elements. ## Rule Details This rule checks all JSX multiline elements and verifies the location of the closing bracket. By default this one must be aligned with the opening tag. Examples of **incorrect** code for this rule: ```jsx ; ; ``` Examples of **correct** code for this rule: ```jsx ; ; ``` ## Rule Options There are two ways to configure this rule. The first form is a string shortcut corresponding to the `location` values specified below. If omitted, it defaults to `"tag-aligned"`. ```js "react/jsx-closing-bracket-location": // -> [, "tag-aligned"] "react/jsx-closing-bracket-location": [, ""] ``` The second form allows you to distinguish between non-empty and self-closing tags. Both properties are optional, and both default to `"tag-aligned"`. You can also disable the rule for one particular type of tag by setting the value to `false`. ```js "react/jsx-closing-bracket-location": [, { "nonEmpty": "" || false, "selfClosing": "" || false }] ``` ### `location` Enforced location for the closing bracket. - `tag-aligned`: must be aligned with the opening tag. - `line-aligned`: must be aligned with the line containing the opening tag. - `after-props`: must be placed right after the last prop. - `props-aligned`: must be aligned with the last prop. Defaults to `tag-aligned`. For backward compatibility, you may pass an object `{ "location": }` that is equivalent to the first string shortcut form. Examples of **incorrect** code for this rule: ```jsx // 'jsx-closing-bracket-location': 1 // 'jsx-closing-bracket-location': [1, 'tag-aligned'] // 'jsx-closing-bracket-location': [1, 'line-aligned'] ; Hello ; // 'jsx-closing-bracket-location': 1 // 'jsx-closing-bracket-location': [1, 'tag-aligned'] var x = ; var x = function() { return Hello ; }; // 'jsx-closing-bracket-location': [1, 'line-aligned'] var x = ; var x = function() { return Hello ; }; // 'jsx-closing-bracket-location': [1, 'after-props'] ; Hello ; // 'jsx-closing-bracket-location': [1, 'props-aligned'] ; Hello ; ``` Examples of **correct** code for this rule: ```jsx // 'jsx-closing-bracket-location': 1 // 'jsx-closing-bracket-location': [1, 'tag-aligned'] // 'jsx-closing-bracket-location': [1, 'line-aligned'] ; Hello ; // 'jsx-closing-bracket-location': 1 // 'jsx-closing-bracket-location': [1, 'tag-aligned'] var x = ; var x = function() { return Hello ; }; // 'jsx-closing-bracket-location': [1, 'line-aligned'] var x = ; var x = function() { return Hello ; }; // 'jsx-closing-bracket-location': [1, {selfClosing: 'after-props'}] ; Hello ; // 'jsx-closing-bracket-location': [1, {selfClosing: 'props-aligned', nonEmpty: 'after-props'}] ; Hello ; ``` ## When Not To Use It If you are not using JSX then you can disable this rule. --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-closing-tag-location.md # Enforce closing tag location for multiline JSX (`react/jsx-closing-tag-location`) πŸ”§ This rule is automatically fixable by the [`--fix` CLI option](https://eslint.org/docs/latest/user-guide/command-line-interface#--fix). Enforce the closing tag location for multiline JSX elements. ## Rule Details This rule checks all JSX multiline elements with children (non-self-closing) and verifies the location of the closing tag. The expectation is that the closing tag is aligned with the opening tag on its own line. Examples of **incorrect** code for this rule: ```jsx marklar ``` ```jsx marklar ``` Examples of **correct** code for this rule: ```jsx marklar ``` ```jsx marklar ``` ## Rule Options There is one way to configure this rule. The configuration is a string shortcut corresponding to the `location` values specified below. If omitted, it defaults to `"tag-aligned"`. ```js "react/jsx-closing-tag-location": // -> [, "tag-aligned"] "react/jsx-closing-tag-location": [, ""] ``` ### `location` Enforced location for the closing tag. - `tag-aligned`: must be aligned with the opening tag. - `line-aligned`: must be aligned with the line containing the opening tag. Defaults to `tag-aligned`. For backward compatibility, you may pass an object `{ "location": }` that is equivalent to the first string shortcut form. Examples of **incorrect** code for this rule: ```jsx // 'jsx-closing-tag-location': 1 // 'jsx-closing-tag-location': [1, 'tag-aligned'] // 'jsx-closing-tag-location': [1, {"location":'tag-aligned'}] Hello ; // 'jsx-closing-tag-location': [1, 'tag-aligned'] // 'jsx-closing-tag-location': [1, {"location":'tag-aligned'}] const App = Foo ; // 'jsx-closing-tag-location': [1, 'line-aligned'] // 'jsx-closing-tag-location': [1, {"location":'line-aligned'}] const App = Foo ; ``` Examples of **correct** code for this rule: ```jsx // 'jsx-closing-tag-location': 1 // 'jsx-closing-tag-location': [1, 'tag-aligned'] // 'jsx-closing-tag-location': [1, {"location":'tag-aligned'}] Hello ; // 'jsx-closing-tag-location': [1, 'tag-aligned'] // 'jsx-closing-tag-location': [1, {"location":'tag-aligned'}] const App = Foo ; // 'jsx-closing-tag-location': [1, 'line-aligned'] // 'jsx-closing-tag-location': [1, {"location":'line-aligned'}] const App = Foo ; ``` ## When Not To Use It If you do not care about closing tag JSX alignment then you can disable this rule. --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-curly-brace-presence.md # Disallow unnecessary JSX expressions when literals alone are sufficient or enforce JSX expressions on literals in JSX children or attributes (`react/jsx-curly-brace-presence`) πŸ”§ This rule is automatically fixable by the [`--fix` CLI option](https://eslint.org/docs/latest/user-guide/command-line-interface#--fix). This rule allows you to enforce curly braces or disallow unnecessary curly braces in JSX props and/or children. For situations where JSX expressions are unnecessary, please refer to [the React doc](https://legacy.reactjs.org/docs/jsx-in-depth.html) and [this page about JSX gotchas](https://github.com/facebook/react/blob/v15.4.0-rc.3/docs/docs/02.3-jsx-gotchas.md#html-entities). ## Rule Details By default, this rule will check for and warn about unnecessary curly braces in both JSX props and children. For the sake of backwards compatibility, prop values that are JSX elements are not considered by default. You can pass in options to enforce the presence of curly braces on JSX props, children, JSX prop values that are JSX elements, or any combination of the three. The same options are available for not allowing unnecessary curly braces as well as ignoring the check. **Note**: it is _highly recommended_ that you configure this rule with an object, and that you set "propElementValues" to "always". The ability to omit curly braces around prop values that are JSX elements is obscure, and intentionally undocumented, and should not be relied upon. ## Rule Options ```js ... "react/jsx-curly-brace-presence": [, { "props": , "children": , "propElementValues": }] ... ``` or alternatively ```js ... "react/jsx-curly-brace-presence": [, ] ... ``` ### Valid options for `` They are `always`, `never` and `ignore` for checking on JSX props and children. - `always`: always enforce curly braces inside JSX props, children, and/or JSX prop values that are JSX Elements - `never`: never allow unnecessary curly braces inside JSX props, children, and/or JSX prop values that are JSX Elements - `ignore`: ignore the rule for JSX props, children, and/or JSX prop values that are JSX Elements If passed in the option to fix, this is how a style violation will get fixed - `always`: wrap a JSX attribute in curly braces/JSX expression and/or a JSX child the same way but also with double quotes - `never`: get rid of curly braces from a JSX attribute and/or a JSX child - All fixing operations use double quotes. For examples: Examples of **incorrect** code for this rule, when configured with `{ props: "always", children: "always" }`: ```jsx Hello world; {'Hello world'}; ``` They can be fixed to: ```jsx {"Hello world"}; {'Hello world'}; ``` Examples of **incorrect** code for this rule, when configured with `{ props: "never", children: "never" }`: ```jsx {'Hello world'}; ; ``` They can be fixed to: ```jsx Hello world; ; ``` Examples of **incorrect** code for this rule, when configured with `{ props: "always", children: "always", "propElementValues": "always" }`: ```jsx />; ``` They can be fixed to: ```jsx } />; ``` Examples of **incorrect** code for this rule, when configured with `{ props: "never", children: "never", "propElementValues": "never" }`: ```jsx } />; ``` They can be fixed to: ```jsx />; ``` ### Alternative syntax The options are also `always`, `never`, and `ignore` for the same meanings. In this syntax, only a string is provided and the default will be set to that option for checking on both JSX props and children. For examples: Examples of **incorrect** code for this rule, when configured with `"always"`: ```jsx Hello world; Hello world; ``` They can be fixed to: ```jsx {"Hello world"}; {"Hello world"}; ``` Examples of **incorrect** code for this rule, when configured with `"never"`: ```jsx {'Hello world'}; ``` It can fixed to: ```jsx Hello world; ``` ## Edge cases The fix also deals with template literals, strings with quotes, and strings with escapes characters. - If the rule is set to get rid of unnecessary curly braces and the template literal inside a JSX expression has no expression, it will throw a warning and be fixed with double quotes. For example: ```jsx {`Hello world`}; ``` will be warned and fixed to: ```jsx Hello world; ``` - If the rule is set to enforce curly braces and the strings have quotes, it will be fixed with double quotes for JSX children and the normal way for JSX attributes. Also, double quotes will be escaped in the fix. For example: ```jsx Hello 'foo' "bar" world; ``` will warned and fixed to: ```jsx {"Hello 'foo' \"bar\" world"}; ``` - If the rule is set to get rid of unnecessary curly braces(JSX expression) and there are characters that need to be escaped in its JSX form, such as quote characters, [forbidden JSX text characters](https://facebook.github.io/jsx/), escaped characters and anything that looks like HTML entity names, the code will not be warned because the fix may make the code less readable. Examples of **correct** code for this rule, even when configured with `"never"`: ```jsx {"Hello \u00b7 world"}; ; /** * there's no way to inject a whitespace into jsx without a container so this * will always be allowed. */ {' '} {' '} {/* comment */ } // the comment makes the container necessary ``` ## When Not To Use It You should turn this rule off if you are not concerned about maintaining consistency regarding the use of curly braces in JSX props and/or children as well as the use of unnecessary JSX expressions. --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-curly-newline.md # Enforce consistent linebreaks in curly braces in JSX attributes and expressions (`react/jsx-curly-newline`) πŸ”§ This rule is automatically fixable by the [`--fix` CLI option](https://eslint.org/docs/latest/user-guide/command-line-interface#--fix). Many style guides require or disallow newlines inside of jsx curly expressions. ## Rule Details This rule enforces consistent linebreaks inside of curlies of jsx curly expressions. ## Rule Options This rule accepts either an object option: ```ts { multiline: "consistent" | "forbid" | "require", // default to 'consistent' singleline: "consistent" | "forbid" | "require", // default to 'consistent' } ``` Option `multiline` takes effect when the jsx expression inside the curlies occupies multiple lines. Option `singleline` takes effect when the jsx expression inside the curlies occupies a single line. - `consistent` enforces either both curly braces have a line break directly inside them, or no line breaks are present. - `forbid` disallows linebreaks directly inside curly braces. - `require` enforces the presence of linebreaks directly inside curlies. or a string option: - `consistent` (default) is an alias for `{ multiline: "consistent", singleline: "consistent" }`. - `never` is an alias for `{ multiline: "forbid", singleline: "forbid" }` or an ### consistent (default) Examples of **incorrect** code for this rule, when configured with `consistent` or `{ multiline: "consistent", singleline: "consistent" }`: ```jsx
{ foo }
{ foo }
{ foo && foo.bar }
``` Examples of **correct** code for this rule: ```jsx
{ foo }
{ foo }
``` ### never Examples of **incorrect** code for this rule, when configured with `never` or `{ multiline: "forbid", singleline: "forbid" }`: ```jsx
{ foo && foo.bar }
{ foo }
{ foo }
``` Examples of **correct** code for this rule: ```jsx
{ foo && foo.bar }
{ foo }
``` ## require Examples of **incorrect** code for this rule, when configured with `{ multiline: "require", singleline: "require" }`: ```jsx
{ foo && foo.bar }
{ foo }
{ foo }
``` Examples of **correct** code for this rule: ```jsx
{ foo && foo.bar }
{ foo }
``` ## When Not To Use It You can turn this rule off if you are not concerned with the consistency of padding linebreaks inside of JSX attributes or expressions. --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-curly-spacing.md # Enforce or disallow spaces inside of curly braces in JSX attributes and expressions (`react/jsx-curly-spacing`) πŸ”§ This rule is automatically fixable by the [`--fix` CLI option](https://eslint.org/docs/latest/user-guide/command-line-interface#--fix). While formatting preferences are very personal, a number of style guides require or disallow spaces between curly braces. ## Rule Details This rule aims to maintain consistency around the spacing inside of JSX attributes and expressions inside element children. It either requires or disallows spaces between those braces and the values inside of them. ## Rule Options There are two main options for the rule: - `{"when": "always"}` enforces a space inside of curly braces - `{"when": "never"}` disallows spaces inside of curly braces (default) There are also two properties that allow specifying how the rule should work with the attributes (`attributes`) and the expressions (`children`). The possible values are: - `true` enables checking for the spacing using the options (default for `attributes`), e.g. `{"attributes": false}` disables checking the attributes - `false` disables checking for the spacing (default for `children`, for backward compatibility), e.g. `{"children": true}` enables checking the expressions - an object containing options that override the global options, e.g. `{"when": "always", "children": {"when": "never"}}` enforces a space inside attributes, but disallows spaces inside expressions ### never Examples of **incorrect** code for this rule, when configured with `{ "when": "never" }`: ```jsx ; ; ; ``` Examples of **correct** code for this rule: ```jsx ; ; ; {firstname}; { firstname }; { firstname }; ``` Examples of **incorrect** code for this rule, when configured with `{ "when": "never", "children": true }`: ```jsx ; ; ; { firstname }; ``` Examples of **correct** code for this rule: ```jsx ; ; ; {firstname}; { firstname }; ``` ### always Examples of **incorrect** code for this rule, when configured with `{ "when": "always" }`: ```jsx ; ; ; ``` Examples of **correct** code for this rule: ```jsx ; ; ; { firstname }; {firstname}; { firstname }; ``` Examples of **incorrect** code for this rule, when configured with `{ "when": "always", "children": true }`: ```jsx ; ; ; {firstname}; ``` Examples of **correct** code for this rule: ```jsx ; ; ; { firstname }; { firstname }; ``` ### Braces spanning multiple lines By default, braces spanning multiple lines are allowed with either setting. If you want to disallow them you can specify an additional `allowMultiline` property with the value `false`: ```json "react/jsx-curly-spacing": [2, {"when": "never", "allowMultiline": false}] ``` Examples of **incorrect** code for this rule, when configured with `"never"` and `"allowMultiline": false`: ```jsx ; ; ; ; ``` Examples of **correct** code for this rule: ```jsx ; ; {firstname}; { firstname }; { firstname }; ``` Examples of **incorrect** code for this rule, when configured with `"always"` and `"allowMultiline": false`: ```jsx ; ; ; ; ``` Examples of **correct** code for this rule: ```jsx ; ; {firstname}; { firstname }; { firstname }; ``` Examples of **incorrect** code for this rule, when configured with `{ "when": "never", "attributes": { "allowMultiline": false }, "children": true }`: ```jsx ; ; { firstname }; ``` Examples of **correct** code for this rule: ```jsx ; {firstname}; { firstname }; ``` ### Granular spacing controls You can specify an additional `spacing` property that is an object with the following possible values: ```json "react/jsx-curly-spacing": [2, {"when": "always", "spacing": { "objectLiterals": "never" }}] ``` - `objectLiterals`: This controls different spacing requirements when the value inside the jsx curly braces is an object literal. All spacing options accept either the string `"always"` or the string `"never"`. Note that the default value for all "spacing" options matches the first "always"/"never" option provided. Examples of **correct** code for this rule, when configured with `"always"` and `{ "objectLiterals": "never" }`: ```jsx ; ``` Examples of **correct** code for this rule, when configured with `"never"` and `{ "objectLiterals": "always" }`: ```jsx ; ``` Please note that spacing of the object literal curly braces themselves is controlled by the built-in [`object-curly-spacing`](https://eslint.org/docs/rules/object-curly-spacing) rule. ### Shorthand options To preserve backward compatibility, two additional options are supported: ```json "react/jsx-curly-spacing": [2, "always"] ``` which is a shorthand for ```json "react/jsx-curly-spacing": [2, {"when": "always"}] ``` and ```json "react/jsx-curly-spacing": [2, "never"] ``` which is a shorthand for ```json "react/jsx-curly-spacing": [2, {"when": "never"}] ``` When using the shorthand options, only attributes will be checked. To specify other options, use another argument: ```json "react/jsx-curly-spacing": [2, "never", { "allowMultiline": false, "spacing": {"objectLiterals": "always"} }] ``` ## When Not To Use It You can turn this rule off if you are not concerned with the consistency around the spacing inside of JSX attributes or expressions. --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-equals-spacing.md # Enforce or disallow spaces around equal signs in JSX attributes (`react/jsx-equals-spacing`) πŸ”§ This rule is automatically fixable by the [`--fix` CLI option](https://eslint.org/docs/latest/user-guide/command-line-interface#--fix). Some style guides require or disallow spaces around equal signs. ## Rule Details This rule will enforce consistency of spacing around equal signs in JSX attributes, by requiring or disallowing one or more spaces before and after `=`. ## Rule Options There are two options for the rule: - `"always"` enforces spaces around the equal sign - `"never"` disallows spaces around the equal sign (default) Depending on your coding conventions, you can choose either option by specifying it in your configuration: ```json "react/jsx-equals-spacing": [2, "always"] ``` ### never Examples of **incorrect** code for this rule, when configured with `"never"`: ```jsx ; ; ; ``` Examples of **correct** code for this rule, when configured with `"never"`: ```jsx ; ; ; ``` ### always Examples of **incorrect** code for this rule, when configured with `"always"`: ```jsx ; ; ; ``` Examples of **correct** code for this rule, when configured with `"always"`: ```jsx ; ; ; ``` ## When Not To Use It You can turn this rule off if you are not concerned with the consistency of spacing around equal signs in JSX attributes. --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-filename-extension.md # Disallow file extensions that may contain JSX (`react/jsx-filename-extension`) ## Rule Details Examples of **incorrect** code for this rule: ```jsx // filename: MyComponent.js function MyComponent() { return
; } ``` Examples of **correct** code for this rule: ```jsx // filename: MyComponent.jsx function MyComponent() { return
; } ``` Beware this rule **only** reports JSX syntax, **not** other non-standard syntax such as experimental features or type annotations. ## Rule Options ### `allow` (default: `"always"`) When to allow a JSX filename extension. By default all files may have a JSX extension. Set this to `as-needed` to only allow JSX file extensions in files that contain JSX syntax. ```js "rules": { "react/jsx-filename-extension": [1, { "allow": "as-needed" }] } ``` ### `extensions` (default: `[".jsx"]`) The set of allowed extensions is configurable. By default '.jsx' is allowed. If you wanted to allow both '.jsx' and '.js', the configuration would be: ```js "rules": { "react/jsx-filename-extension": [1, { "extensions": [".js", ".jsx"] }] } ``` ### `ignoreFilesWithoutCode` (default: `false`) If enabled, files that do not contain code (i.e. are empty, contain only whitespaces or comments) will not be rejected. ```js "rules": { "react/jsx-filename-extension": [1, { "ignoreFilesWithoutCode": true }] } ``` ## When Not To Use It If you don't care about restricting the file extensions that may contain JSX. --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-first-prop-new-line.md # Enforce proper position of the first property in JSX (`react/jsx-first-prop-new-line`) πŸ”§ This rule is automatically fixable by the [`--fix` CLI option](https://eslint.org/docs/latest/user-guide/command-line-interface#--fix). Ensure correct position of the first property. Note: The fixer does not include indentation. Please rerun lint to correct those errors. ## Rule Details This rule checks whether the first property of all JSX elements is correctly placed. There are the possible configurations: - `always`: The first property should always be placed on a new line. - `never` : The first property should never be placed on a new line, e.g. should always be on the same line as the Component opening tag. - `multiline`: The first property should always be placed on a new line when the JSX tag takes up multiple lines. - `multiprop`: The first property should never be placed on a new line unless there are multiple properties. - `multiline-multiprop`: The first property should always be placed on a new line if the JSX tag takes up multiple lines and there are multiple properties. This is the `default` value. Examples of **incorrect** code for this rule, when configured with `"always"`: ```jsx ``` Examples of **correct** code for this rule, when configured with `"always"`: ```jsx ``` Examples of **incorrect** code for this rule, when configured with `"never"`: ```jsx ``` Examples of **correct** code for this rule, when configured with `"never"`: ```jsx ``` Examples of **incorrect** code for this rule, when configured with `"multiline"`: ```jsx ``` ```jsx ``` Examples of **correct** code for this rule, when configured with `"multiline"`: ```jsx ``` Examples of **incorrect** code for this rule, when configured with `"multiline-multiprop"`: ```jsx ``` Examples of **correct** code for this rule, when configured with `"multiline-multiprop"`: ```jsx ``` ## Rule Options ```jsx "react/jsx-first-prop-new-line": `"always" | "never" | "multiline" | "multiprop" | "multiline-multiprop"` ``` ## When Not To Use It If you are not using JSX then you can disable this rule. --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-fragments.md # Enforce shorthand or standard form for React fragments (`react/jsx-fragments`) πŸ”§ This rule is automatically fixable by the [`--fix` CLI option](https://eslint.org/docs/latest/user-guide/command-line-interface#--fix). In JSX, a React [fragment] is created either with `...`, or, using the shorthand syntax, `<>...`. ## Rule Details This rule allows you to enforce one way or the other. Support for fragments was added in React v16.2, so the rule will warn on either of these forms if an older React version is specified in [shared settings][shared_settings]. ## Rule Options ```js ... "react/jsx-fragments": [, ] ... ``` ### `syntax` mode This is the default mode. It will enforce the shorthand syntax for React fragments, with one exception. [Keys or attributes are not supported by the shorthand syntax][short_syntax], so the rule will not warn on standard-form fragments that use those. Examples of **incorrect** code for this rule: ```jsx ``` Examples of **correct** code for this rule: ```jsx <> ``` ```jsx ``` ### `element` mode This mode enforces the standard form for React fragments. Examples of **incorrect** code for this rule: ```jsx <> ``` Examples of **correct** code for this rule: ```jsx ``` ```jsx ``` [fragment]: https://reactjs.org/docs/fragments.html [shared_settings]: /README.md#configuration [short_syntax]: https://reactjs.org/docs/fragments.html#short-syntax --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-handler-names.md # Enforce event handler naming conventions in JSX (`react/jsx-handler-names`) Ensures that any component or prop methods used to handle events are correctly prefixed. ## Rule Details Examples of **incorrect** code for this rule: ```jsx ``` ```jsx ``` Examples of **correct** code for this rule: ```jsx ``` ```jsx ``` ## Rule Options ```js ... "react/jsx-handler-names": [, { "eventHandlerPrefix": , "eventHandlerPropPrefix": , "checkLocalVariables": , "checkInlineFunction": , "ignoreComponentNames": Array }] ... ``` - `eventHandlerPrefix`: Prefix for component methods used as event handlers. Defaults to `handle` - `eventHandlerPropPrefix`: Prefix for props that are used as event handlers. Defaults to `on` - `checkLocalVariables`: Determines whether event handlers stored as local variables are checked. Defaults to `false` - `checkInlineFunction`: Determines whether event handlers set as inline functions are checked. Defaults to `false` - `ignoreComponentNames`: Array of glob strings, when matched with component name, ignores the rule on that component. Defaults to `[]` ## When Not To Use It If you are not using JSX, or if you don't want to enforce specific naming conventions for event handlers. --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-indent-props.md # Enforce props indentation in JSX (`react/jsx-indent-props`) πŸ”§ This rule is automatically fixable by the [`--fix` CLI option](https://eslint.org/docs/latest/user-guide/command-line-interface#--fix). This option validates a specific indentation style for props. ## Rule Details This rule is aimed to enforce consistent indentation style. The default style is `4 spaces`. Examples of **incorrect** code for this rule: ```jsx // 2 spaces indentation // no indentation // 1 tab indentation ``` ## Rule Options It takes an option as the second parameter which can either be the indent mode or an object to define further settings. The indent mode can be `"tab"` for tab-based indentation, a positive number for space indentations or `"first"` for aligning the first prop for each line with the tag's first prop. Note that using the `"first"` option allows very inconsistent indentation unless you also enable a rule that enforces the position of the first prop. If the second parameter is an object, it can be used to specify the indent mode as well as the option `ignoreTernaryOperator`, which causes the indent level not to be increased by a `?` or `:` operator (default is `false`). ```js ... "react/jsx-indent-props": [, 'tab'||'first'|] ... ``` Examples of **incorrect** code for this rule: ```jsx // 2 spaces indentation // [2, 2] // tab indentation // [2, 'tab'] // aligned with first prop // [2, 'first'] ``` Examples of **correct** code for this rule: ```jsx // 2 spaces indentation // [2, 2] // tab indentation // [2, 'tab'] // no indentation // [2, 0] // aligned with first prop // [2, 'first'] // indent level increase on ternary operator (default setting) // [2, 2] ? // no indent level increase on ternary operator // [2, { indentMode: 2, ignoreTernaryOperator: true} ] ? ``` ## When Not To Use It If you are not using JSX then you can disable this rule. --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-indent.md # Enforce JSX indentation (`react/jsx-indent`) πŸ”§ This rule is automatically fixable by the [`--fix` CLI option](https://eslint.org/docs/latest/user-guide/command-line-interface#--fix). This option validates a specific indentation style for JSX. Note: The fixer will fix whitespace and tabs indentation. ## Rule Details This rule is aimed to enforce consistent indentation style. The default style is `4 spaces`. Examples of **incorrect** code for this rule: ```jsx // 2 spaces indentation // no indentation // 1 tab indentation ``` ## Rule Options It takes an option as the second parameter which can be `"tab"` for tab-based indentation or a positive number for space indentations. To enable checking the indentation of attributes or add indentation to logical expressions, use the third parameter to turn on the `checkAttributes` (default is false) and `indentLogicalExpressions` (default is false) respectively. ```js ... "react/jsx-indent": [, 'tab'|, {checkAttributes: , indentLogicalExpressions: }] ... ``` Examples of **incorrect** code for this rule: ```jsx // 2 spaces indentation // [2, 2] // tab indentation // [2, 'tab'] // [2, 2, {checkAttributes: true}]
hi
} /> }>
// [2, 2, {indentLogicalExpressions: true}] {condition && ( )} ``` Examples of **correct** code for this rule: ```jsx // 2 spaces indentation // [2, 2] // tab indentation // [2, 'tab'] // no indentation // [2, 0] // [2, 2, {checkAttributes: false}]
hi
} /> }>
// [2, 2, {indentLogicalExpressions: true}] {condition && ( )} ``` ## When Not To Use It If you are not using JSX then you can disable this rule. --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-key.md # Disallow missing `key` props in iterators/collection literals (`react/jsx-key`) πŸ’Ό This rule is enabled in the β˜‘οΈ `recommended` [config](https://github.com/jsx-eslint/eslint-plugin-react/#shareable-configs). Warn if an element that likely requires a `key` prop--namely, one present in an array literal or an arrow function expression. ## Rule Details Examples of **incorrect** code for this rule: ```jsx [, , ]; ``` ```jsx data.map(x => {x}); ``` ```jsx Array.from([1, 2, 3], (x) => {x}); ``` ```jsx ``` In the last example the key is being spread, which is currently possible, but discouraged in favor of the statically provided key. Examples of **correct** code for this rule: ```jsx [, , ]; ``` ```jsx data.map((x) => {x}); ``` ```jsx Array.from([1, 2, 3], (x) => {x}); ``` ```jsx ``` ## Rule Options ```js ... "react/jsx-key": [, { "checkFragmentShorthand": }] ... ``` ### `checkFragmentShorthand` (default: `false`) When `true` the rule will check if usage of the [shorthand fragment syntax][short_syntax] requires a key. This option was added to avoid a breaking change and will be the default in the next major version. Examples of **incorrect** code for this rule: ```jsx [<>, <>, <>]; ``` ```jsx data.map(x => <>{x}); ``` ### `checkKeyMustBeforeSpread` (default: `false`) When `true` the rule will check if key prop after spread to avoid [createElement fallback](https://github.com/facebook/react/issues/20031#issuecomment-710346866). Examples of **incorrect** code for this rule: ```jsx ; ``` ### `warnOnDuplicates` (default: `false`) When `true` the rule will check for any duplicate key prop values. Examples of **incorrect** code for this rule: ```jsx const spans = [ , , ]; ``` ## When Not To Use It If you are not using JSX then you can disable this rule. Also, if you have some prevalent situation where you use arrow functions to return JSX that will not be held in an iterable, you may want to disable this rule. [short_syntax]: https://reactjs.org/docs/fragments.html#short-syntax --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-max-depth.md # Enforce JSX maximum depth (`react/jsx-max-depth`) This option validates a specific depth for JSX. ## Rule Details Examples of **incorrect** code for this rule: ```jsx ``` ## Rule Options It takes an option as the second parameter which can be a positive number for depth count. ```js ... "react/jsx-max-depth": [, { "max": }] ... ``` Examples of **incorrect** code for this rule: ```jsx // [2, { "max": 1 }] // [2, { "max": 1 }] const foobar = ; {foobar} // [2, { "max": 2 }] ``` Examples of **correct** code for this rule: ```jsx // [2, { "max": 1 }] // [2,{ "max": 2 }] // [2, { "max": 3 }] ``` ## When Not To Use It If you are not using JSX then you can disable this rule. --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-max-props-per-line.md # Enforce maximum of props on a single line in JSX (`react/jsx-max-props-per-line`) πŸ”§ This rule is automatically fixable by the [`--fix` CLI option](https://eslint.org/docs/latest/user-guide/command-line-interface#--fix). Limiting the maximum of props on a single line can improve readability. Note: The fixer does not include indentation. Please rerun lint to correct those errors. ## Rule Details This rule checks all JSX elements and verifies that the number of props per line do not exceed the maximum allowed. Props are considered to be in a new line if there is a line break between the start of the prop and the end of the previous prop. A spread attribute counts as one prop. This rule is off by default and when on the default maximum of props on one line is `1`. Examples of **incorrect** code for this rule: ```jsx ; ; ``` Examples of **correct** code for this rule: ```jsx ; ; ``` ## Rule Options ```js ... "react/jsx-max-props-per-line": [, { "maximum": , "when": }] ... // OR ... "react/jsx-max-props-per-line": [, { "maximum": { "single": , "multi": } }] ... ``` ### `maximum` Maximum number of props allowed on a single line. Default to `1`. Examples of **incorrect** code for this rule: ```jsx // [1, { "maximum": 2 }] ; ``` Examples of **correct** code for this rule: ```jsx // [1, { "maximum": 2 }] ; ``` Maximum can be specified as object `{ single: 1, multi: 1 }` to specify maximum allowed number of props for single line and multiple line tags. ### `when` _when only applied if `maximum` is specified as number._ Possible values: - `always` (default) - Always check for max props per line. - `multiline` - Only check for max props per line when jsx tag spans multiple lines. Examples of **incorrect** code for this rule: ```jsx // [1, { "when": "always" }] ``` Examples of **correct** code for this rule: ```jsx // [1, { "when": "multiline" }] ``` ## When Not To Use It If you are not using JSX then you can disable this rule. --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-newline.md # Require or prevent a new line after jsx elements and expressions (`react/jsx-newline`) πŸ”§ This rule is automatically fixable by the [`--fix` CLI option](https://eslint.org/docs/latest/user-guide/command-line-interface#--fix). ## Rule Details This is a stylistic rule intended to make JSX code more readable by requiring or preventing lines between adjacent JSX elements and expressions. ## Rule Options ```json5 ... "react/jsx-newline": [, { "prevent": , "allowMultilines": }] ... ``` - enabled: for enabling the rule. 0=off, 1=warn, 2=error. Defaults to 0. - prevent: optional boolean. If `true` prevents empty lines between adjacent JSX elements and expressions. Defaults to `false`. - allowMultilines: optional boolean. If `true` and `prevent` is also equal to `true`, it allows newlines after multiline JSX elements and expressions. Defaults to `false`. ## Examples Examples of **incorrect** code for this rule, when configured with `{ "prevent": false }`: ```jsx
``` ```jsx
{showSomething === true && }
``` ```jsx
{showSomething === true && } {showSomethingElse === true ? ( ) : ( )}
``` Examples of **correct** code for this rule, when configured with `{ "prevent": false }`: ```jsx
{showSomething === true && } {showSomethingElse === true ? ( ) : ( )}
``` Examples of **incorrect** code for this rule, when configured with `{ "prevent": true }`: ```jsx
{showSomething === true && } {showSomethingElse === true ? ( ) : ( )}
``` Examples of **correct** code for this rule, when configured with `{ "prevent": true }`: ```jsx
``` ```jsx
{showSomething === true && }
``` ```jsx
{showSomething === true && } {showSomethingElse === true ? ( ) : ( )}
``` Examples of **incorrect** code for this rule, when configured with `{ "prevent": true, "allowMultilines": true }`: ```jsx
{showSomething === true && } {showSomethingElse === true ? ( ) : ( )}
``` Examples of **correct** code for this rule, when configured with `{ "prevent": true, "allowMultilines": true }`: ```jsx
{showSomething === true && } {showSomethingElse === true ? ( ) : ( )}
``` ## When Not To Use It You can turn this rule off if you are not concerned with spacing between your JSX elements and expressions. --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-no-bind.md # Disallow `.bind()` or arrow functions in JSX props (`react/jsx-no-bind`) Using `bind` on a function or declaring a function in the render method of a component or the body of a functional component, and then passing that function as a prop will mean that the brand new function that is created on every single render will be considered a completely different function. This can affect performance in some situations, as it may cause unnecessary re-renders if a brand new function is passed as a prop to a component that uses reference equality check on the prop to determine if it should update, such as a component wrapped with [`memo`](https://react.dev/reference/react/memo#memo), or if the prop is used in any hook's "dependency array". Note that this behavior is different for `ref` props, which is a special case in React that **does not** cause re-renders when a brand new function is passed. See [`ignore-refs`](#ignorerefs) below for more information. ## Rule Details Examples of **incorrect** code for this rule: ```jsx ``` ```jsx console.log('Hello!')}> ``` ```jsx function onClick() { console.log('Hello!'); } ``` Examples of **correct** code for this rule: ```jsx ``` ## Rule Options ```js "react/jsx-no-bind": [, { "ignoreDOMComponents": || false, "ignoreRefs": || false, "allowArrowFunctions": || false, "allowFunctions": || false, "allowBind": || false }] ``` ### `ignoreDOMComponents` Examples of **correct** code for this rule, when `ignoreDOMComponents` is `true`: ```jsx
console.log("Hello!")} /> ); }; ``` Otherwise, the idiomatic way to avoid redefining callbacks on every render would be to memoize them using the [`useCallback`](https://legacy.reactjs.org/docs/hooks-reference.html#usecallback) hook: ```jsx const Button = () => { const [text, setText] = useState("Before click"); const onClick = useCallback(() => { setText("After click"); }, [setText]); // Array of dependencies for which the memoization should update return ( ); }; ``` ## When Not To Use It If you do not use JSX or do not want to enforce that `bind`, functions declared in the render method of a component, or functions declared in the body of a functional component are not used in props, then you can disable this rule. --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-no-comment-textnodes.md # Disallow comments from being inserted as text nodes (`react/jsx-no-comment-textnodes`) πŸ’Ό This rule is enabled in the β˜‘οΈ `recommended` [config](https://github.com/jsx-eslint/eslint-plugin-react/#shareable-configs). This rule prevents comment strings (e.g. beginning with `//` or `/*`) from being accidentally injected as a text node in JSX statements. ## Rule Details Examples of **incorrect** code for this rule: ```jsx var Hello = createReactClass({ render: function() { return (
// empty div
); } }); var Hello = createReactClass({ render: function() { return (
/* empty div */
); } }); ``` Examples of **correct** code for this rule: ```jsx var Hello = createReactClass({ displayName: 'Hello', render: function() { return
{/* empty div */}
; } }); var Hello = createReactClass({ displayName: 'Hello', render: function() { return
; } }); var Hello = createReactClass({ displayName: 'Hello', render: function() { return
; } }); ``` ## Legitimate uses It's possible you may want to legitimately output comment start characters (`//` or `/*`) in a JSX text node. In which case, you can do the following: ```jsx var Hello = createReactClass({ render: function() { return (
{'/* This will be output as a text node */'}
); } }); ``` --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-no-constructed-context-values.md # Disallows JSX context provider values from taking values that will cause needless rerenders (`react/jsx-no-constructed-context-values`) This rule prevents non-stable values (i.e. object identities) from being used as a value for `Context.Provider`. ## Rule Details One way to resolve this issue may be to wrap the value in a `useMemo()`. If it's a function then `useCallback()` can be used as well. If you _expect_ the context to be rerun on each render, then consider adding a comment/lint suppression explaining why. ## Examples Examples of **incorrect** code for this rule: ```jsx return ( ... ) ``` ```jsx import React from 'react'; const MyContext = React.createContext(); function Component() { function foo() {} return (); } ``` Examples of **correct** code for this rule: ```jsx const foo = useMemo(() => ({foo: 'bar'}), []); return ( ... ) ``` ```jsx const SomeContext = createContext(); const Component = () => ; ``` ## Legitimate Uses React Context, and all its child nodes and Consumers are rerendered whenever the value prop changes. Because each Javascript object carries its own _identity_, things like object expressions (`{foo: 'bar'}`) or function expressions get a new identity on every run through the component. This makes the context think it has gotten a new object and can cause needless rerenders and unintended consequences. This can be a pretty large performance hit because not only will it cause the context providers and consumers to rerender with all the elements in its subtree, the processing for the tree scan react does to render the provider and find consumers is also wasted. --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-no-duplicate-props.md # Disallow duplicate properties in JSX (`react/jsx-no-duplicate-props`) πŸ’Ό This rule is enabled in the β˜‘οΈ `recommended` [config](https://github.com/jsx-eslint/eslint-plugin-react/#shareable-configs). Creating JSX elements with duplicate props can cause unexpected behavior in your application. ## Rule Details Examples of **incorrect** code for this rule: ```jsx ; ``` Examples of **correct** code for this rule: ```jsx ; ``` ## Rule Options ```js ... "react/jsx-no-duplicate-props": [, { "ignoreCase": }] ... ``` ### `ignoreCase` When `true` the rule ignores the case of the props. Default to `false`. ## When Not To Use It If you are not using JSX then you can disable this rule. --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-no-leaked-render.md # Disallow problematic leaked values from being rendered (`react/jsx-no-leaked-render`) πŸ”§ This rule is automatically fixable by the [`--fix` CLI option](https://eslint.org/docs/latest/user-guide/command-line-interface#--fix). Using the `&&` operator to render some element conditionally in JSX can cause unexpected values being rendered, or even crashing the rendering. ## Rule Details This rule aims to prevent dangerous leaked values from being rendered since they can cause unexpected values reaching the final DOM or even crashing your render method. In React, you might end up rendering unexpected values like `0` or `NaN`. In React Native, your render method will even crash if you render these values: ```jsx const Example = () => { return ( <> {0 && } {/* React: renders undesired 0 */} {/* React Native: crashes πŸ’₯ */} {NaN && } {/* React: renders undesired NaN */} {/* React Native: crashes πŸ’₯ */} {'' && } {/* React: renders nothing */} {/* React Native, with React < 18: crashes πŸ’₯ */} ) } ``` This can be avoided by: - coercing the conditional to a boolean: `{!!someValue && }` - transforming the binary expression into a ternary expression which returns `null` for falsy values: `{someValue ? : null}` This rule is autofixable; check the Options section to read more about the different strategies available. Examples of **incorrect** code for this rule: ```jsx const Component = ({ count, title }) => { return
{count && title}
} ``` ```jsx const Component = ({ count }) => { return
{count && There are {count} results}
} ``` ```jsx const Component = ({ elements }) => { return
{elements.length && }
} ``` ```jsx const Component = ({ nestedCollection }) => { return (
{nestedCollection.elements.length && }
) } ``` ```jsx const Component = ({ elements }) => { return
{elements[0] && }
} ``` ```jsx const Component = ({ numberA, numberB }) => { return
{(numberA || numberB) && {numberA + numberB}}
} ``` ```jsx // If the condition is a boolean value, this rule will report the logical expression // since it can't infer the type of the condition. const Component = ({ someBool }) => { return
{someBool && {numberA + numberB}}
} ``` Examples of **correct** code for this rule: ```jsx const Component = ({ elements }) => { return
{elements}
} ``` ```jsx // An OR condition it's considered valid since it's assumed as a way // to render some fallback if the first value is falsy, not to render something conditionally. const Component = ({ customTitle }) => { return
{customTitle || defaultTitle}
} ``` ```jsx const Component = ({ elements }) => { return
There are {elements.length} elements
} ``` ```jsx const Component = ({ elements, count }) => { return
{!count && 'No results found'}
} ``` ```jsx const Component = ({ elements }) => { return
{!!elements.length && }
} ``` ```jsx const Component = ({ elements }) => { return
{Boolean(elements.length) && }
} ``` ```jsx const Component = ({ elements }) => { return
{elements.length > 0 && }
} ``` ```jsx const Component = ({ elements }) => { return
{elements.length ? : null}
} ``` ```jsx const Component = ({ elements }) => { return
{elements.length ? : }
} ``` ## Rule Options The supported options are: ### `validStrategies` An array containing `"coerce"`, `"ternary"`, or both (default: `["ternary", "coerce"]`) - Decide which strategies are considered valid to prevent leaked renders (at least 1 is required). The "coerce" option will transform the conditional of the JSX expression to a boolean. The "ternary" option transforms the binary expression into a ternary expression returning `null` for falsy values. The first option from the array will be the strategy used when autofixing, so the order of the values matters. It can be set like: ```json5 { // ... "react/jsx-no-leaked-render": [, { "validStrategies": ["ternary", "coerce"] }] // ... } ``` Assuming the following options: `{ "validStrategies": ["ternary"] }` Examples of **incorrect** code for this rule, with the above configuration: ```jsx const Component = ({ count, title }) => { return
{count && title}
} ``` ```jsx const Component = ({ count, title }) => { return
{!!count && title}
} ``` Examples of **correct** code for this rule, with the above configuration: ```jsx const Component = ({ count, title }) => { return
{count ? title : null}
} ``` ```jsx const Component = ({ count, title, empty }) => { return
{count ? title : empty}
} ``` Assuming the following options: `{ "validStrategies": ["coerce"] }` Examples of **incorrect** code for this rule, with the above configuration: ```jsx const Component = ({ count, title }) => { return
{count && title}
} ``` ```jsx const Component = ({ count, title }) => { return
{count ? title : null}
} ``` Examples of **correct** code for this rule, with the above configuration: ```jsx const Component = ({ count, title }) => { return
{!!count && title}
} ``` ```jsx const Component = ({ count, title, empty }) => { return
{count ? title : empty}
} ``` ## When Not To Use It If you are working in a typed-codebase which encourages you to always use boolean conditions, this rule can be disabled. ## Further Reading - [React docs: Inline If with Logical && Operator](https://reactjs.org/docs/conditional-rendering.html#inline-if-with-logical--operator) - [Good advice on JSX conditionals - Beware of zero](https://thoughtspile.github.io/2022/01/17/jsx-conditionals/) - [Twitter: rendering falsy values in React and React Native](https://twitter.com/kadikraman/status/1507654900376875011?s=21&t=elEXXbHhzWthrgKaPRMjNg) --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-no-literals.md # Disallow usage of string literals in JSX (`react/jsx-no-literals`) There are a few scenarios where you want to avoid string literals in JSX. You may want to enforce consistency, reduce syntax highlighting issues, or ensure that strings are part of a translation system. ## Rule Details By default this rule requires that you wrap all literal strings in a JSX container `{'TEXT'}`. Examples of **incorrect** code for this rule: ```jsx var Hello =
test
; ``` Examples of **correct** code for this rule: ```jsx var Hello =
{'test'}
; ``` ```jsx var Hello =
{'test'}
; ``` ## Rule Options The supported options are: - `noStrings` (default: `false`) - Enforces no string literals used as children, wrapped or unwrapped. - `allowedStrings` - An array of unique string values that would otherwise warn, but will be ignored. - `ignoreProps` (default: `false`) - When `true` the rule ignores literals used in props, wrapped or unwrapped. - `noAttributeStrings` (default: `false`) - Enforces no string literals used in attributes when set to `true`. - `elementOverrides` - An object where the keys are the element names and the values are objects with the same options as above. This allows you to specify different options for different elements. ### `elementOverrides` The `elementOverrides` option allows you to specify different options for different elements. This is useful when you want to enforce different rules for different elements. For example, you may want to allow string literals in `Button` elements, but not in the rest of your application. The element name only accepts component names. HTML element tag names are not supported. Component names are case-sensitive and should exactly match the name of the component as it is used in the JSX. It can also be the name of a compound component (ie. `Modal.Button`). Specifying options creates a new context for the rule, so the rule will only apply the new options to the specified element and its children (if `applyToNestedElements` is `true` - see below). This means that the root rule options will not apply to the specified element. In addition to the options above (`noStrings`, `allowedStrings`, `noAttributeStrings` and `ignoreProps`), you can also specify the the following options that are specific to `elementOverrides`: - `allowElement` (default: `false`) - When `true` the rule will allow the specified element to have string literals as children, wrapped or unwrapped without warning. - `applyToNestedElements` (default: `true`) - When `false` the rule will not apply the current options set to nested elements. This is useful when you want to apply the rule to a specific element, but not to its children. **Note**: As this rule has no way of differentiating between different componets with the same name, it is recommended to use this option with specific components that are unique to your application. #### `elementOverrides` Examples The following are **correct** examples that demonstrate how to use the `elementOverrides` option: ```js // "react/jsx-no-literals": [, {"elementOverrides": { "Button": {"allowElement": true} }}] var Hello =
{'test'}
; var World = ; ``` ```js // "react/jsx-no-literals": [, {"elementOverrides": { "Text": {"allowElement": true} }}] var World = Hello world; ``` ```js // "react/jsx-no-literals": [, {"elementOverrides": { "Text": {"allowElement": true, "applyToNestedElements": false} }}] var linkText = 'world'; var World = Hello {linkText}; ``` ```js // "react/jsx-no-literals": [, {"noStrings": true, "elementOverrides": { "Button": {"noStrings": false} }}] // OR // "react/jsx-no-literals": [, {"noStrings": true, "elementOverrides": { "Button": {} }}] var test = 'test' var Hello =
{test}
; var World = ; ``` ## Examples To use, you can specify as follows: ```js "react/jsx-no-literals": [, {"noStrings": true, "allowedStrings": ["allowed"], "ignoreProps": false, "noAttributeStrings": true }] ``` Examples of **incorrect** code for this rule, with the above configuration: ```jsx var Hello =
test
; ``` ```jsx var Hello =
{'test'}
; ``` ```jsx var Hello =
{'test'}
; ``` ```jsx var Hello =
test
; ``` ```jsx var Hello =
; ``` ```jsx var Hello =
; ``` ```jsx var Hello =
; ``` Examples of **correct** code for this rule: ```jsx // When using something like `react-intl` var Hello =
``` ```jsx // When using something similar to Rails translations var Hello =
{translate('my.translation.key')}
``` ```jsx // an allowed string var Hello =
allowed
``` ```jsx // an allowed string surrounded by only whitespace var Hello =
allowed
; ``` ```jsx // a string value stored within a variable used as an attribute's value var Hello =
{imageDescription}
; ``` ```jsx // spread props object var Hello = ``` ```jsx // use variable for prop values var Hello =
``` ```jsx // cache class Comp1 extends Component { asdf() {} render() { return (
{'asdjfl'} test {'foo'}
); } } ``` ## When Not To Use It If you do not want to enforce any style JSX literals, then you can disable this rule. --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-no-script-url.md # Disallow usage of `javascript:` URLs (`react/jsx-no-script-url`) **In React 16.9** any URLs starting with `javascript:` [scheme](https://wiki.whatwg.org/wiki/URL_schemes#javascript:_URLs) log a warning. React considers the pattern as a dangerous attack surface, see [details](https://reactjs.org/blog/2019/08/08/react-v16.9.0.html#deprecating-javascript-urls). **In a future major release**, React will throw an error if it encounters a `javascript:` URL. ## Rule Details Examples of **incorrect** code for this rule: ```jsx ``` Examples of **correct** code for this rule: ```jsx ``` This rule takes the `linkComponents` setting into account. ## Rule Options This rule accepts array option (optional) and object option (optional). ### Array option (default `[]`) ```json { "react/jsx-no-script-url": [ "error", [ { "name": "Link", "props": ["to"] }, { "name": "Foo", "props": ["href", "to"] } ] ] } ``` Allows you to indicate a specific list of properties used by a custom component to be checked. #### name Component name. #### props List of properties that should be validated. Examples of **incorrect** code for this rule, when configured with the above options: ```jsx ``` ### Object option #### includeFromSettings (default `false`) Indicates if the `linkComponents` config in [global shared settings](https://github.com/jsx-eslint/eslint-plugin-react/blob/master/README.md#configuration) should also be taken into account. If enabled, components and properties defined in settings will be added to the list provided in first option (if provided): ```json { "react/jsx-no-script-url": [ "error", [ { "name": "Link", "props": ["to"] }, { "name": "Foo", "props": ["href", "to"] } ], { "includeFromSettings": true } ] } ``` If only global settings should be used for this rule, the array option can be omitted: ```jsonc { // same as ["error", [], { "includeFromSettings": true }] "react/jsx-no-script-url": ["error", { "includeFromSettings": true }] } ``` --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-no-target-blank.md # Disallow `target="_blank"` attribute without `rel="noreferrer"` (`react/jsx-no-target-blank`) πŸ’Ό This rule is enabled in the β˜‘οΈ `recommended` [config](https://github.com/jsx-eslint/eslint-plugin-react/#shareable-configs). πŸ”§ This rule is automatically fixable by the [`--fix` CLI option](https://eslint.org/docs/latest/user-guide/command-line-interface#--fix). When creating a JSX element that has an `a` tag, it is often desired to have the link open in a new tab using the `target='_blank'` attribute. Using this attribute unaccompanied by `rel='noreferrer'`, however, is a severe security vulnerability (see [noreferrer docs](https://html.spec.whatwg.org/multipage/links.html#link-type-noreferrer) and [noopener docs](https://html.spec.whatwg.org/multipage/links.html#link-type-noopener) for more details) This rules requires that you accompany `target='_blank'` attributes with `rel='noreferrer'`. ## Rule Details This rule aims to prevent user generated link hrefs and form actions from creating security vulnerabilities by requiring `rel='noreferrer'` for external link hrefs and form actions, and optionally any dynamically generated link hrefs and form actions. ## Rule Options ```js ... "react/jsx-no-target-blank": [, { "allowReferrer": , "enforceDynamicLinks": , "warnOnSpreadAttributes": , "links": , "forms": , }] ... ``` - `enabled`: for enabling the rule. - `allowReferrer`: optional boolean. If `true` does not require `noreferrer` (i. e. `noopener` alone is enough, this leaves IE vulnerable). Defaults to `false`. - `enforceDynamicLinks`: optional string, `'always'` or `'never'`. - `warnOnSpreadAttributes`: optional boolean. Defaults to `false`. - `links`: prevent usage of unsafe `target='_blank'` inside links, defaults to `true`. - `forms`: prevent usage of unsafe `target='_blank'` inside forms, defaults to `false`. ### `enforceDynamicLinks` #### always `{"enforceDynamicLinks": "always"}` enforces the rule if the href is a dynamic link (default) Examples of **incorrect** code for this rule, when configured with `{ "enforceDynamicLinks": "always" }`: ```jsx var Hello = var Hello = ``` Examples of **correct** code for this rule: ```jsx var Hello =

var Hello = var Hello = var Hello = var Hello = var Hello = ``` #### never `{"enforceDynamicLinks": "never"}` does not enforce the rule if the href is a dynamic link Examples of **correct** code for this rule, when configured with `{ "enforceDynamicLinks": "never" }`: ```jsx var Hello = ``` ### `warnOnSpreadAttributes` Spread attributes are a handy way of passing programmatically-generated props to components, but may contain unsafe props e.g. ```jsx const unsafeProps = { href: "https://example.com", target: "_blank", }; ``` Defaults to false. If false, this rule will ignore all spread attributes. If true, this rule will treat all spread attributes as if they contain an unsafe combination of props, unless specifically overridden by props _after_ the last spread attribute prop e.g. the following would not be violations: ```jsx ``` ### `links` / `forms` When option `forms` is set to `true`, the following is considered an error: ```jsx var Hello =
; ``` When option `links` is set to `true`, the following is considered an error: ```jsx var Hello = ``` ### Custom link components This rule supports the ability to use custom components for links, such as `` which is popular in libraries like `react-router`, `next.js` and `gatsby`. To enable this, define your custom link components in the global [shared settings](https://github.com/jsx-eslint/eslint-plugin-react/blob/master/README.md#configuration) under the `linkComponents` configuration area. Once configured, this rule will check those components as if they were `` elements. Examples of **incorrect** code for this rule: ```jsx var Hello = var Hello = ``` Examples of **correct** code for this rule: ```jsx var Hello = var Hello = var Hello = var Hello = ``` ### Custom form components This rule supports the ability to use custom components for forms. To enable this, define your custom form components in the global [shared settings](https://github.com/jsx-eslint/eslint-plugin-react/blob/master/README.md#configuration) under the `formComponents` configuration area. Once configured, this rule will check those components as if they were `
` elements. ## When To Override It Modern browsers (Chrome β‰₯ 88, Edge β‰₯ 88, Firefox β‰₯ 79 and Safari β‰₯ 12.2) automatically imply `rel="noopener"`. Therefore this rule is no longer needed, if legacy browsers are not supported. See and for more details. For links to a trusted host (e.g. internal links to your own site, or links to a another host you control, where you can be certain this security vulnerability does not exist), you may want to keep the HTTP Referer header for analytics purposes. If you do not support Internet Explorer (any version), Chrome < 49, Opera < 36, Firefox < 52, desktop Safari < 10.1 or iOS Safari < 10.3, you may set `allowReferrer` to `true`, keep the HTTP Referer header and only add `rel="noopener"` to your links. ## When Not To Use It If you do not have any external links or forms, you can disable this rule. --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-no-undef.md # Disallow undeclared variables in JSX (`react/jsx-no-undef`) πŸ’Ό This rule is enabled in the β˜‘οΈ `recommended` [config](https://github.com/jsx-eslint/eslint-plugin-react/#shareable-configs). This rule helps locate potential ReferenceErrors resulting from misspellings or missing components. ## Rule Details Examples of **incorrect** code for this rule: ```jsx ; ``` ```jsx // will ignore Text in the global scope and warn var Hello = React.createClass({ render: function() { return Hello; } }); module.exports = Hello; ``` Examples of **correct** code for this rule: ```jsx var Hello = require('./Hello'); ; ``` ## Rule Options ```js ... "react/jsx-no-undef": [, { "allowGlobals": }] ... ``` ### `allowGlobals` When `true` the rule will consider the global scope when checking for defined Components. Examples of **correct** code for this rule, when `"allowGlobals"` is `true`: ```jsx var Text = require('./Text'); var Hello = React.createClass({ render: function() { return Hello; } }); module.exports = Hello; ``` ## When Not To Use It If you are not using JSX then you can disable this rule. --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-no-useless-fragment.md # Disallow unnecessary fragments (`react/jsx-no-useless-fragment`) πŸ”§ This rule is automatically fixable by the [`--fix` CLI option](https://eslint.org/docs/latest/user-guide/command-line-interface#--fix). A fragment is redundant if it contains only one child, or if it is the child of a html element, and is not a [keyed fragment](https://reactjs.org/docs/fragments.html#keyed-fragments). ## Rule Details Examples of **incorrect** code for this rule: ```jsx <>{foo} <>

<>foo

<> foo foo
<>
{showFullName ? <>{fullName} : <>{firstName}} ``` Examples of **correct** code for this rule: ```jsx {foo} <> <>foo {bar} <> {foo} const cat = <>meow <>
{item.value} {showFullName ? fullName : firstName} ``` ## Rule Options ### `allowExpressions` When `true` single expressions in a fragment will be allowed. This is useful in places like Typescript where `string` does not satisfy the expected return type of `JSX.Element`. A common workaround is to wrap the variable holding a string in a fragment and expression. Examples of **correct** code for the rule, when `"allowExpressions"` is `true`: ```jsx <>{foo} <> {foo} ``` --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-one-expression-per-line.md # Require one JSX element per line (`react/jsx-one-expression-per-line`) πŸ”§ This rule is automatically fixable by the [`--fix` CLI option](https://eslint.org/docs/latest/user-guide/command-line-interface#--fix). This option limits every line in JSX to one expression each. Note: The fixer will insert line breaks between any expression that are on the same line. ## Rule Details Examples of **incorrect** code for this rule: ```jsx World { 'World' } { this.world() } { 'Hello' }{ ' ' }{ 'World' } ``` Examples of **correct** code for this rule: ```jsx World { 'World' } { this.world() } { 'Hello' } { ' ' } { 'World' } ``` ## Rule Options ```js ... "react/jsx-one-expression-per-line": [, { "allow": "none"|"literal"|"single-child" }] ... ``` ### `allow` Defaults to `none`. Examples of **correct** code for this rule, when configured as `"literal"`: ```jsx Hello ``` Examples of **correct** code for this rule, when configured as `"single-child"`: ```jsx Hello {"Hello"} ``` Examples of **correct** code for this rule, when configured as `"non-jsx"`: ```jsx Hello {someVariable} Hello {} there! ``` --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-pascal-case.md # Enforce PascalCase for user-defined JSX components (`react/jsx-pascal-case`) Enforces coding style that user-defined JSX components are defined and referenced in PascalCase. Note that since React's JSX uses the upper vs. lower case convention to distinguish between local component classes and HTML tags this rule will not warn on components that start with a lower case letter. ## Rule Details Examples of **incorrect** code for this rule: ```jsx ``` ```jsx ``` Examples of **correct** code for this rule: ```jsx
``` ```jsx ``` ```jsx
``` ```jsx ``` ## Rule Options ```js ... "react/jsx-pascal-case": [, { allowAllCaps: , allowNamespace: , allowLeadingUnderscore: , ignore: }] ... ``` - `enabled`: for enabling the rule. 0=off, 1=warn, 2=error. Defaults to 0. - `allowAllCaps`: optional boolean set to `true` to allow components name in all caps (default to `false`). - `allowLeadingUnderscore`: optional boolean set to `true` to allow components name with that starts with an underscore (default to `false`). - `allowNamespace`: optional boolean set to `true` to ignore namespaced components (default to `false`). - `ignore`: optional string-array of component names to ignore during validation (supports [minimatch](https://github.com/isaacs/minimatch)-style globs). ### `allowAllCaps` Examples of **correct** code for this rule, when `allowAllCaps` is `true`: ```jsx ``` ### `allowNamespace` Examples of **correct** code for this rule, when `allowNamespace` is `true`: ```jsx ``` ### `allowLeadingUnderscore` Examples of **correct** code for this rule, when `allowLeadingUnderscore` is `true`: ```jsx <_AllowedComponent /> <_AllowedComponent>
``` **WARNING:** Adding a leading underscore to the name of a component does **NOT** affect the visibility or accessibility of that component. Attempting to use leading underscores to enforce privacy of your components is an error. ## When Not To Use It If you are not using JSX. --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-props-no-multi-spaces.md # Disallow multiple spaces between inline JSX props (`react/jsx-props-no-multi-spaces`) πŸ”§ This rule is automatically fixable by the [`--fix` CLI option](https://eslint.org/docs/latest/user-guide/command-line-interface#--fix). Enforces that there is exactly one space between all attributes and after tag name and the first attribute in the same line. ## Rule Details Examples of **incorrect** code for this rule: ```jsx ``` ```jsx ``` ```jsx ``` Examples of **correct** code for this rule: ```jsx ``` ```jsx ``` ```jsx ``` ## When Not To Use It If you are not using JSX or don't care about the space between two props in the same line. If you have enabled the core rule `no-multi-spaces` with eslint >= 3, you don't need this rule. --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-props-no-spread-multi.md # Disallow JSX prop spreading the same identifier multiple times (`react/jsx-props-no-spread-multi`) Enforces that any unique expression is only spread once. Generally spreading the same expression twice is an indicator of a mistake since any attribute between the spreads may be overridden when the intent was not to. Even when that is not the case this will lead to unnecessary computations being performed. ## Rule Details Examples of **incorrect** code for this rule: ```jsx ``` Examples of **correct** code for this rule: ```jsx ``` ## When Not To Use It When spreading the same expression multiple times yields different results. --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-props-no-spreading.md # Disallow JSX prop spreading (`react/jsx-props-no-spreading`) Enforces that there is no spreading for any JSX attribute. This enhances readability of code by being more explicit about what props are received by the component. It is also good for maintainability by avoiding passing unintentional extra props and allowing react to emit warnings when invalid HTML props are passed to HTML elements. ## Rule Details Examples of **incorrect** code for this rule: ```jsx ``` Examples of **correct** code for this rule: ```jsx const {src, alt} = props; const {one_prop, two_prop} = otherProps; {alt} ``` ## Rule Options ```js ... "react/jsx-props-no-spreading": [, { "html": "ignore" | "enforce", "custom": "ignore" | "enforce", "explicitSpread": "ignore" | "enforce", "exceptions": [] }] ... ``` ### html `html` set to `ignore` will ignore all html jsx tags like `div`, `img` etc. Default is set to `enforce`. Examples of **correct** code for this rule, when `html` is set to `ignore`: ```jsx ``` Examples of **incorrect** code for this rule, when `html` is set to `ignore`: ```jsx ``` ### custom `custom` set to `ignore` will ignore all custom jsx tags like `App`, `MyCustomComponent` etc. Default is set to `enforce`. Examples of **correct** code for this rule, when `custom` is set to `ignore`: ```jsx ``` Examples of **incorrect** code for this rule, when `custom` is set to `ignore`: ```jsx ``` ### explicitSpread `explicitSpread` set to `ignore` will ignore spread operators that are explicitly listing all object properties within that spread. Default is set to `enforce`. Examples of **correct** code for this rule, when `explicitSpread` is set to `ignore`: ```jsx ``` ### exceptions An "exception" will always flip the resulting html or custom setting for that component - ie, html set to `ignore`, with an exception of `div` will enforce on an `div`; custom set to `enforce` with an exception of `Foo` will ignore `Foo`. ```js { "exceptions": ["Image", "img"] } ``` Examples of **correct** code for this rule: ```jsx const {src, alt} = props; ``` Examples of **incorrect** code for this rule: ```jsx ``` ```js { "html": "ignore", "exceptions": ["MyCustomComponent", "img"] } ``` Examples of **correct** code for this rule: ```jsx const {src, alt} = props; const {one_prop, two_prop} = otherProps; {alt} ``` Examples of **incorrect** code for this rule: ```jsx ``` ## When Not To Use It If you are not using JSX or have lots of props to be passed or the props spreading is used inside HOC. --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-sort-default-props.md # Enforce defaultProps declarations alphabetical sorting (`react/jsx-sort-default-props`) ❌ This rule is deprecated. It was replaced by [`react/sort-default-props`](sort-default-props.md). Some developers prefer to sort `defaultProps` declarations alphabetically to be able to find necessary declarations easier at a later time. Others feel that it adds complexity and becomes a burden to maintain. ## Rule Details This rule checks all components and verifies that all `defaultProps` declarations are sorted alphabetically. A spread attribute resets the verification. The default configuration of the rule is case-sensitive. Examples of **incorrect** code for this rule: ```jsx var Component = createReactClass({ ... getDefaultProps: function() { return { z: "z", a: "a", b: "b" }; }, ... }); class Component extends React.Component { ... } Component.defaultProps = { z: "z", a: "a", b: "b" }; class Component extends React.Component { static defaultProps = { z: "z", y: "y", a: "a" } render() { return
; } } const Component = (props) => (...); Component.defaultProps = { z: "z", y: "y", a: "a" }; const defaults = { b: "b" }; const types = { a: PropTypes.string, b: PropTypes.string, c: PropTypes.string' }; function StatelessComponentWithSpreadInPropTypes({ a, b, c }) { return
{a}{b}{c}
; } StatelessComponentWithSpreadInPropTypes.propTypes = types; StatelessComponentWithSpreadInPropTypes.defaultProps = { c: "c", a: "a", ...defaults, }; export default class ClassWithSpreadInPropTypes extends BaseClass { static propTypes = { a: PropTypes.string, b: PropTypes.string, c: PropTypes.string, d: PropTypes.string, e: PropTypes.string, f: PropTypes.string } static defaultProps = { b: "b", a: "a", ...c.defaultProps, f: "f", e: "e", ...d.defaultProps } } ``` Examples of **correct** code for this rule: ```jsx var Component = createReactClass({ ... getDefaultProps: function() { return { a: "a", b: "b", c: "c" }; }, ... }); class Component extends React.Component { ... } Component.defaultProps = { a: "a", b: "b", c: "c" }; class Component extends React.Component { static defaultProps = { a: PropTypes.any, b: PropTypes.any, c: PropTypes.any } render() { return
; } } const Component = (props) => (...); Component.defaultProps = { a: "a", y: "y", z: "z" }; const defaults = { b: "b" }; const types = { a: PropTypes.string, b: PropTypes.string, c: PropTypes.string' }; function StatelessComponentWithSpreadInPropTypes({ a, b, c }) { return
{a}{b}{c}
; } StatelessComponentWithSpreadInPropTypes.propTypes = types; StatelessComponentWithSpreadInPropTypes.defaultProps = { a: "a", c: "c", ...defaults, }; export default class ClassWithSpreadInPropTypes extends BaseClass { static propTypes = { a: PropTypes.string, b: PropTypes.string, c: PropTypes.string, d: PropTypes.string, e: PropTypes.string, f: PropTypes.string } static defaultProps = { a: "a", b: "b", ...c.defaultProps, e: "e", f: "f", ...d.defaultProps } } ``` ## Rule Options ```js ... "react/jsx-sort-default-props": [, { "ignoreCase": , }] ... ``` ### `ignoreCase` When `true` the rule ignores the case-sensitivity of the declarations order. ## When Not To Use It This rule is a formatting preference and not following it won't negatively affect the quality of your code. If alphabetizing `defaultProps` declarations isn't a part of your coding standards, then you can leave this rule off. --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-sort-props.md # Enforce props alphabetical sorting (`react/jsx-sort-props`) πŸ”§ This rule is automatically fixable by the [`--fix` CLI option](https://eslint.org/docs/latest/user-guide/command-line-interface#--fix). Some developers prefer to sort props names alphabetically to be able to find necessary props easier at the later time. Others feel that it adds complexity and becomes burden to maintain. ## Rule Details This rule checks all JSX components and verifies that all props are sorted alphabetically. A spread attribute resets the verification. The default configuration of the rule is case-sensitive. Examples of **incorrect** code for this rule: ```jsx ; ``` Examples of **correct** code for this rule: ```jsx ; ; ``` ## Rule Options ```js ... "react/jsx-sort-props": [, { "callbacksLast": , "shorthandFirst": , "shorthandLast": , "multiline": "ignore" | "first" | "last", "ignoreCase": , "noSortAlphabetically": , "reservedFirst": |>, "locale": "auto" | "any valid locale" }] ... ``` ### `ignoreCase` When `true` the rule ignores the case-sensitivity of the props order. Examples of **correct** code for this rule ```jsx ; ``` ### `callbacksLast` When `true`, callbacks must be listed after all other props, even if `shorthandLast` is set : ```jsx ``` ### `shorthandFirst` When `true`, short hand props must be listed before all other props, but still respecting the alphabetical order: ```jsx ``` ### `shorthandLast` When `true`, short hand props must be listed after all other props (unless `callbacksLast` is set), but still respecting the alphabetical order: ```jsx ``` ### `multiline` Enforced sorting for multiline props - `ignore`: Multiline props will not be taken in consideration for sorting. - `first`: Multiline props must be listed before all other props (unless `shorthandFirst` is set), but still respecting the alphabetical order. - `last`: Multiline props must be listed after all other props (unless either `callbacksLast` or `shorthandLast` are set), but still respecting the alphabetical order. Defaults to `ignore`. ```jsx // 'jsx-sort-props': [1, { multiline: 'first' }] // 'jsx-sort-props': [1, { multiline: 'last' }] ``` ### `noSortAlphabetically` When `true`, alphabetical order is **not** enforced: ```jsx ``` ### `reservedFirst` This can be a boolean or an array option. When `reservedFirst` is defined, React reserved props (`children`, `dangerouslySetInnerHTML` - **only for DOM components**, `key`, and `ref`) must be listed before all other props, but still respecting the alphabetical order: ```jsx
``` If given as an array, the array's values will override the default list of reserved props. **Note**: the values in the array may only be a **subset** of React reserved props. With `reservedFirst: ["key"]`, the following will **not** warn: ```jsx ``` ### `locale` Defaults to `"auto"`, meaning, the locale of the current environment. Any other string provided here may be passed to `String.prototype.localeCompare` - note that an unknown or invalid locale may throw an exception and crash. ## When Not To Use It This rule is a formatting preference and not following it won't negatively affect the quality of your code. If alphabetizing props isn't a part of your coding standards, then you can leave this rule off. --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-space-before-closing.md # Enforce spacing before closing bracket in JSX (`react/jsx-space-before-closing`) ❌ This rule is deprecated. It was replaced by [`react/jsx-tag-spacing`](jsx-tag-spacing.md). πŸ”§ This rule is automatically fixable by the [`--fix` CLI option](https://eslint.org/docs/latest/user-guide/command-line-interface#--fix). Please use the `"beforeSelfClosing"` option of the [jsx-tag-spacing](https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-tag-spacing.md) rule instead. Enforce or forbid spaces before the closing bracket of self-closing JSX elements. ## Rule Details This rule checks if there is one or more spaces before the closing bracket of self-closing JSX elements. ## Rule Options This rule takes one argument. If it is `"always"` then it warns whenever a space is missing before the closing bracket. If `"never"` then it warns if a space is present before the closing bracket. The default value of this option is `"always"`. Examples of **incorrect** code for this rule, when configured with `"always"`: ```jsx ``` Examples of **correct** code for this rule, when configured with `"always"`: ```jsx ``` Examples of **incorrect** code for this rule, when configured with `"never"`: ```jsx ``` Examples of **correct** code for this rule, when configured with `"never"`: ```jsx ``` ## When Not To Use It You can turn this rule off if you are not concerned with the consistency of spacing before closing brackets. --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-tag-spacing.md # Enforce whitespace in and around the JSX opening and closing brackets (`react/jsx-tag-spacing`) πŸ”§ This rule is automatically fixable by the [`--fix` CLI option](https://eslint.org/docs/latest/user-guide/command-line-interface#--fix). Enforce or forbid spaces after the opening bracket, before the closing bracket, before the closing bracket of self-closing elements, and between the angle bracket and slash of JSX closing or self-closing elements. ## Rule Details This rule checks the whitespace inside and surrounding the JSX syntactic elements. ## Rule Options This rule takes one argument, an object with 4 possible keys: `closingSlash`, `beforeSelfClosing`, `afterOpening`, and `beforeClosing`. Each key can receive the value `"allow"` to disable that specific check. The default values are: ```json { "closingSlash": "never", "beforeSelfClosing": "always", "afterOpening": "never", "beforeClosing": "allow" } ``` The options for each sub-option are documented in the following subsections. ### `closingSlash` This check can be set to `"always"`, `"never"` or `"allow"` (to disable it). If it is `"never"`, the check warns whenever a space is separating the two characters in the JSX tokens ``. If it is `"always"` then it warns whenever a space is missing separating the mentioned two characters. The default value of this check is `"never"`. Examples of **incorrect** code for this rule, when configured with `{ "closingSlash": "never" }`: ```jsx < /Provider> ``` Examples of **correct** code for this rule, when configured with `{ "closingSlash": "never" }`: ```jsx ``` Examples of **incorrect** code for this rule, when configured with `{ "closingSlash": "always" }`: ```jsx ``` Examples of **correct** code for this rule, when configured with `{ "closingSlash": "always" }`: ```jsx < /Goodbye> ``` ### `beforeSelfClosing` This check can be set to `"always"`, `"never"`, `"proportional-always"`, or `"allow"` (to disable it). If it is `"always"`, the check warns whenever a space is missing before the closing bracket. If `"never"` then it warns if a space is present before the closing bracket. The default value of this check is `"always"`. Examples of **incorrect** code for this rule, when configured with `{ "beforeSelfClosing": "always" }`: ```jsx ``` Examples of **correct** code for this rule, when configured with `{ "beforeSelfClosing": "always" }`: ```jsx ``` Examples of **incorrect** code for this rule, when configured with `{ "beforeSelfClosing": "never" }`: ```jsx ``` Examples of **correct** code for this rule, when configured with `{ "beforeSelfClosing": "never" }`: ```jsx ``` Examples of **incorrect** code for this rule, when configured with `{ "beforeSelfClosing": "proportional-always" }`: ```jsx ``` Examples of **correct** code for this rule, when configured with `{ "beforeSelfClosing": "proportional-always" }`: ```jsx ``` ### `afterOpening` This check can be set to `"always"`, `"never"`, `"allow-multiline"` or `"allow"` (to disable it). If it is `"always"`, the check warns whenever a space is missing after the opening bracket of either a JSX opening element or closing element. If `"never"` then it warns if a space is present after the opening bracket of either a JSX opening element or closing element. If `"allow-multiline"` then it behaves like `"never"`, but allows if the separator includes a newline character. The default value of this check is `"never"`. Examples of **incorrect** code for this rule, when configured with `{ "afterOpening": "always" }`: ```jsx ``` Examples of **correct** code for this rule, when configured with `{ "afterOpening": "always" }`: ```jsx < Hello> < Hello firstName="John"/> < Hello firstName="John" lastName="Smith" /> ``` Examples of **incorrect** code for this rule, when configured with `{ "afterOpening": "never" }`: ```jsx < Hello> < Hello firstName="John"/> < Hello firstName="John" lastName="Smith" /> ``` Examples of **correct** code for this rule, when configured with `{ "afterOpening": "never" }`: ```jsx ``` Examples of **incorrect** code for this rule, when configured with `{ "afterOpening": "allow-multiline" }`: ```jsx < Hello> < Hello firstName="John"/> < Hello firstName="John" lastName="Smith" /> ``` Examples of **correct** code for this rule, when configured with `{ "afterOpening": "allow-multiline" }`: ```jsx < Hello firstName="John" lastName="Smith" /> ``` ### `beforeClosing` This check can be set to `"always"`, `"never"`, `"proportional-always"`, or `"allow"` (to disable it). If it is `"always"` the check warns whenever whitespace is missing before the closing bracket of a JSX opening element or whenever a space is missing before the closing bracket closing element. If `"never"`, then it warns if a space is present before the closing bracket of either a JSX opening element or closing element. This rule will never warn for self closing JSX elements. The default value of this check is `"allow"`. Examples of **incorrect** code for this rule, when configured with `{ "beforeClosing": "always" }`: ```jsx ``` Examples of **correct** code for this rule, when configured with `{ "beforeClosing": "always" }`: ```jsx ``` Examples of **incorrect** code for this rule, when configured with `{ "beforeClosing": "never" }`: ```jsx ``` Examples of **correct** code for this rule, when configured with `{ "beforeClosing": "never" }`: ```jsx ``` Examples of **incorrect** code for this rule, when configured with `{ "beforeClosing": "proportional-always" }`: ```jsx Goodbye ``` Examples of **correct** code for this rule, when configured with `{ "beforeClosing": "proportional-always" }`: ```jsx Goodbye ``` ## When Not To Use It You can turn this rule off if you are not concerned with the consistency of spacing in or around JSX brackets. --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-uses-react.md # Disallow React to be incorrectly marked as unused (`react/jsx-uses-react`) πŸ’ΌπŸš« This rule is enabled in the β˜‘οΈ `recommended` [config](https://github.com/jsx-eslint/eslint-plugin-react/#shareable-configs). This rule is _disabled_ in the πŸƒ `jsx-runtime` [config](https://github.com/jsx-eslint/eslint-plugin-react/#shareable-configs). JSX expands to a call to `React.createElement`, a file which includes `React` but only uses JSX should consider the `React` variable as used. If you are using the @jsx pragma this rule will mark the designated variable and not the `React` one. This rule has no effect if the `no-unused-vars` rule is not enabled. You can use the [shared settings](/README.md#configuration) to specify a custom pragma. ## Rule Details Examples of **incorrect** code for this rule: ```js var React = require('react'); // nothing to do with React ``` ```jsx /** @jsx Foo */ var React = require('react'); var Hello =
Hello {this.props.name}
; ``` Examples of **correct** code for this rule: ```jsx var React = require('react'); var Hello =
Hello {this.props.name}
; ``` ```jsx /** @jsx Foo */ var Foo = require('foo'); var Hello =
Hello {this.props.name}
; ``` ## When Not To Use It If you are not using JSX, if React is declared as global variable, or if you do not use the `no-unused-vars` rule. If you are using the [new JSX transform from React 17](https://reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html#removing-unused-react-imports), you should disable this rule by extending [`react/jsx-runtime`](https://github.com/jsx-eslint/eslint-plugin-react/blob/HEAD/index.js#L163-L176) in your eslint config (add `"plugin:react/jsx-runtime"` to `"extends"`). --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-uses-vars.md # Disallow variables used in JSX to be incorrectly marked as unused (`react/jsx-uses-vars`) πŸ’Ό This rule is enabled in the β˜‘οΈ `recommended` [config](https://github.com/jsx-eslint/eslint-plugin-react/#shareable-configs). Since 0.17.0 the `eslint` `no-unused-vars` rule does not detect variables used in JSX ([see details](https://eslint.org/blog/2015/03/eslint-0.17.0-released#changes-to-jsxreact-handling)). This rule will find variables used in JSX and mark them as used. This rule only has an effect when the `no-unused-vars` rule is enabled. ## Rule Details Examples of **incorrect** code for this rule: ```js var Hello = require('./Hello'); ``` Examples of **correct** code for this rule: ```jsx var Hello = require('./Hello'); ; ``` ## When Not To Use It If you are not using JSX or if you do not use the `no-unused-vars` rule then you can disable this rule. --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-wrap-multilines.md # Disallow missing parentheses around multiline JSX (`react/jsx-wrap-multilines`) πŸ”§ This rule is automatically fixable by the [`--fix` CLI option](https://eslint.org/docs/latest/user-guide/command-line-interface#--fix). Wrapping multiline JSX in parentheses can improve readability and/or convenience. ## Rule Details This rule optionally takes a second parameter in the form of an object, containing places to apply the rule. By default, all the syntax listed below will be checked except the conditions out of declaration or assignment, logical expressions and JSX attributes, but these can be explicitly disabled. Any syntax type missing in the object will follow the default behavior displayed below. ```json { "declaration": "parens", "assignment": "parens", "return": "parens", "arrow": "parens", "condition": "ignore", "logical": "ignore", "prop": "ignore" } ``` Note: conditions are checked by default in declarations or assignments. ## Rule Options Examples of **incorrect** code for this rule, when configured with `parens` or `parens-new-line`: ```jsx var Hello = createReactClass({ render: function() { return

Hello {this.props.name}

; } }); ``` Examples of **incorrect** code for this rule, when configured with `parens-new-line`: ```jsx var Hello = createReactClass({ render: function() { return (

Hello {this.props.name}

); } }); ``` Examples of **correct** code for this rule, when configured with either `parens` or `parens-new-line`: ```jsx var singleLineJSX =

Hello

var Hello = createReactClass({ render: function() { return (

Hello {this.props.name}

); } }); ``` Examples of **incorrect** code for this rule, when configured with `never`: ```jsx var singleLineJSX =

Hello

var Hello = createReactClass({ render: function() { return (

Hello {this.props.name}

); } }); ``` Examples of **correct** code for this rule, when configured with `never`: ```jsx var singleLineJSX =

Hello

var Hello = createReactClass({ render: function() { return

Hello {this.props.name}

; } }); ``` ### `declaration` Examples of **incorrect** code for this rule, when configured with `{ declaration: "parens" }`: ```jsx var hello =

Hello

; ``` Examples of **correct** code for this rule, when configured with `{ declaration: "parens" }`: ```jsx var hello = (

Hello

); ``` ```jsx var hello = (

Hello

); ``` Examples of **incorrect** code for this rule, when configured with `{ declaration: "parens-new-line" }`: ```jsx var hello =

Hello

; ``` ```jsx var hello = (

Hello

); ``` Examples of **correct** code for this rule, when configured with `{ declaration: "parens-new-line" }`. ```jsx var hello = (

Hello

); ``` Examples of **incorrect** code for this rule, when configured with `{ declaration: "never" }`: ```jsx var hello = (

Hello

); ``` ```jsx var hello = (

Hello

); ``` Examples of **correct** code for this rule, when configured with `{ declaration: "never" }`. ```jsx var hello =

Hello

; ``` ### `assignment` Examples of **incorrect** code for this rule, when configured with `{ assignment: "parens" }`. ```jsx var hello; hello =

Hello

; ``` Examples of **correct** code for this rule, when configured with `{ assignment: "parens" }`. ```jsx var hello; hello = (

Hello

); ``` ```jsx var hello; hello = (

Hello

); ``` Examples of **incorrect** code for this rule, when configured with `{ assignment: "parens-new-line" }`. ```jsx var hello; hello =

Hello

; ``` ```jsx var hello; hello = (

Hello

); ``` Examples of **correct** code for this rule, when configured with `{ assignment: "parens-new-line" }`. ```jsx var hello; hello = (

Hello

); ``` Examples of **incorrect** code for this rule, when configured with `{ assignment: "never" }`. ```jsx var hello; hello = (

Hello

); ``` ```jsx var hello; hello = (

Hello

); ``` Examples of **correct** code for this rule, when configured with `{ assignment: "never" }`. ```jsx var hello; hello =

Hello

; ``` ### `return` Examples of **incorrect** code for this rule, when configured with `{ return: "parens" }`. ```jsx function hello() { return

Hello

; } ``` Examples of **correct** code for this rule, when configured with `{ return: "parens" }`. ```jsx function hello() { return (

Hello

); } ``` ```jsx function hello() { return (

Hello

); } ``` Examples of **incorrect** code for this rule, when configured with `{ return: "parens-new-line" }`. ```jsx function hello() { return

Hello

; } ``` ```jsx function hello() { return (

Hello

); } ``` Examples of **correct** code for this rule, when configured with `{ return: "parens-new-line" }`. ```jsx function hello() { return (

Hello

); } ``` Examples of **incorrect** code for this rule, when configured with `{ return: "never" }`. ```jsx function hello() { return (

Hello

); } ``` ```jsx function hello() { return (

Hello

); } ``` Examples of **correct** code for this rule, when configured with `{ return: "never" }`. ```jsx function hello() { return

Hello

; } ``` ### `arrow` Examples of **incorrect** code for this rule, when configured with `{ arrow: "parens" }`. ```jsx var hello = () =>

World

; ``` Examples of **correct** code for this rule, when configured `{ arrow: "parens" }`. ```jsx var hello = () => (

World

); ``` ```jsx var hello = () => (

World

); ``` Examples of **incorrect** code for this rule, when configured with `{ arrow: "parens-new-line" }`. ```jsx var hello = () =>

World

; ``` ```jsx var hello = () => (

World

); ``` Examples of **correct** code for this rule, when configured with `{ arrow: "parens-new-line" }`. ```jsx var hello = () => (

World

); ``` Examples of **incorrect** code for this rule, when configured with `{ arrow: "never" }`. ```jsx var hello = () => (

World

); ``` ```jsx var hello = () => (

World

); ``` Examples of **correct** code for this rule, when configured with `{ arrow: "never" }`. ```jsx var hello = () =>

World

; ``` ### `condition` Examples of **incorrect** code for this rule, when configured with `{ condition: "parens" }`. ```jsx
{foo ?

Hello

: null}
``` Examples of **correct** code for this rule, when configured with `{ condition: "parens" }`. ```jsx
{foo ? (

Hello

) : null}
``` ```jsx
{foo ? (

Hello

): null}
``` Examples of **incorrect** code for this rule, when configured with `{ condition: "parens-new-line" }`. ```jsx
{foo ?

Hello

: null}
``` ```jsx
{foo ? (

Hello

) : null}
``` Examples of **correct** code for this rule, when configured with `{ condition: "parens-new-line" }`. ```jsx
{foo ? (

Hello

): null}
``` Examples of **incorrect** code for this rule, when configured with `{ condition: "never" }`. ```jsx
{foo ? (

Hello

) : null}
``` ```jsx
{foo ? (

Hello

): null}
``` Examples of **correct** code for this rule, when configured with `{ condition: "never" }`. ```jsx
{foo ?

Hello

: null}
``` ### `logical` Examples of **incorrect** code for this rule, when configured with `{ logical: "parens" }`. ```jsx
{foo &&

Hello World

}
``` Examples of **correct** code for this rule, when configured with `{ logical: "parens" }`. ```jsx
{foo && (

Hello World

) }
``` ```jsx
{foo && (

Hello World

)}
``` Examples of **incorrect** code for this rule, when configured with `{ logical: "parens-new-line" }`. ```jsx
{foo &&

Hello World

}
``` ```jsx
{foo && (

Hello World

) }
``` Examples of **correct** code for this rule, when configured with `{ logical: "parens-new-line" }`. ```jsx
{foo && (

Hello World

)}
``` Examples of **incorrect** code for this rule, when configured with `{ logical: "never" }`. ```jsx
{foo && (

Hello World

) }
``` ```jsx
{foo && (

Hello World

)}
``` Examples of **correct** code for this rule, when configured with `{ logical: "never" }`. ```jsx
{foo &&

Hello World

}
``` ### `prop` Examples of **incorrect** code for this rule, when configured with `{ prop: "parens" }`. ```jsx

Hello

}>

Hello

; ``` Examples of **correct** code for this rule, when configured with `{ prop: "parens" }`. ```jsx

Hello

)}>

Hello

; ``` ```jsx

Hello

)}>

Hello

; ``` Examples of **incorrect** code for this rule, when configured with `{ prop: "parens-new-line" }`. ```jsx

Hello

}>

Hello

; ``` ```jsx

Hello

)}>

Hello

; ``` Examples of **correct** code for this rule, when configured with `{ prop: "parens-new-line" }`. ```jsx

Hello

)}>

Hello

; ``` Examples of **incorrect** code for this rule, when configured with `{ prop: "never" }`. ```jsx

Hello

)}>

Hello

; ``` ```jsx

Hello

)}>

Hello

; ``` Examples of **correct** code for this rule, when configured with `{ prop: "never" }`. ```jsx

Hello

}>

Hello

; ``` --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/no-access-state-in-setstate.md # Disallow when this.state is accessed within setState (`react/no-access-state-in-setstate`) Usage of `this.state` inside `setState` calls might result in errors when two state calls are called in batch and thus referencing old state and not the current state. ## Rule Details This rule should prevent usage of `this.state` inside `setState` calls. ## Examples An example can be an increment function: ```javascript function increment() { this.setState({value: this.state.value + 1}); } ``` If two `setState` operations are grouped together in a batch, they both evaluate the old state. Given that `state.value` is 1: ```javascript this.setState({value: this.state.value + 1}) // 2 this.setState({value: this.state.value + 1}) // 2, not 3 ``` This can be avoided with using callbacks which takes the previous state as first argument: ```javascript function increment() { this.setState(prevState => ({value: prevState.value + 1})); } ``` Then react will call the argument with the correct and updated state, even when things happen in batches. And the example above will be something like: ```javascript setState({value: 1 + 1}) setState({value: 2 + 1}) ``` --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/no-adjacent-inline-elements.md # Disallow adjacent inline elements not separated by whitespace (`react/no-adjacent-inline-elements`) Adjacent inline elements not separated by whitespace will bump up against each other when viewed in an unstyled manner, which usually isn't desirable. ## Rule Details Examples of **incorrect** code for this rule: ```jsx
React.createElement("div", undefined, [React.createElement("a"), React.createElement("span")]); ``` Examples of **correct** code for this rule: ```jsx
React.createElement("div", undefined, [React.createElement("a"), " ", React.createElement("a")]); ``` --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/no-array-index-key.md # Disallow usage of Array index in keys (`react/no-array-index-key`) Warn if an element uses an Array index in its `key`. The `key` is used by React to [identify which items have changed, are added, or are removed and should be stable](https://react.dev/learn/rendering-lists#why-does-react-need-keys). It's a bad idea to use the array index since it doesn't uniquely identify your elements. In cases where the array is sorted or an element is added to the beginning of the array, the index will be changed even though the element representing that index may be the same. This results in unnecessary renders. ## Rule Details Examples of **incorrect** code for this rule: ```jsx things.map((thing, index) => ( )); things.map((thing, index) => ( React.cloneElement(thing, { key: index }) )); things.forEach((thing, index) => { otherThings.push(); }); things.filter((thing, index) => { otherThings.push(); }); things.some((thing, index) => { otherThings.push(); }); things.every((thing, index) => { otherThings.push(); }); things.find((thing, index) => { otherThings.push(); }); things.findIndex((thing, index) => { otherThings.push(); }); things.flatMap((thing, index) => ( )); things.reduce((collection, thing, index) => ( collection.concat() ), []); things.reduceRight((collection, thing, index) => ( collection.concat() ), []); React.Children.map(this.props.children, (child, index) => ( React.cloneElement(child, { key: index }) )) Children.forEach(this.props.children, (child, index) => ( React.cloneElement(child, { key: index }) )) ``` Examples of **correct** code for this rule: ```jsx things.map((thing) => ( )); things.map((thing) => ( React.cloneElement(thing, { key: thing.id }) )); things.forEach((thing) => { otherThings.push(); }); things.filter((thing) => { otherThings.push(); }); things.some((thing) => { otherThings.push(); }); things.every((thing) => { otherThings.push(); }); things.find((thing) => { otherThings.push(); }); things.findIndex((thing) => { otherThings.push(); }); things.reduce((collection, thing) => ( collection.concat() ), []); things.reduceRight((collection, thing) => ( collection.concat() ), []); ``` ## When Not To Use It If there is nothing unique about the items, for example [you are breaking an array down in to chunks](https://github.com/jsx-eslint/eslint-plugin-react/issues/1123), then you may want to disable this rule with an override. --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/no-arrow-function-lifecycle.md # Lifecycle methods should be methods on the prototype, not class fields (`react/no-arrow-function-lifecycle`) πŸ”§ This rule is automatically fixable by the [`--fix` CLI option](https://eslint.org/docs/latest/user-guide/command-line-interface#--fix). It is not necessary to use arrow function for lifecycle methods. This makes things harder to test, conceptually less performant (although in practice, performance will not be affected, since most engines will optimize efficiently), and can break hot reloading patterns. ## Rule Details The following patterns are considered warnings: ```jsx class Hello extends React.Component { render = () => { return
; } } var AnotherHello = createReactClass({ render: () => { return
; }, }); ``` The following patterns are **not** considered warnings: ```jsx class Hello extends React.Component { render() { return
; } } var AnotherHello = createReactClass({ render() { return
; }, }); ``` ## When Not To Use It If you don't care about performance of your application or conceptual correctness of class property placement, you can disable this rule. --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/no-children-prop.md # Disallow passing of children as props (`react/no-children-prop`) πŸ’Ό This rule is enabled in the β˜‘οΈ `recommended` [config](https://github.com/jsx-eslint/eslint-plugin-react/#shareable-configs). Children should always be actual children, not passed in as a prop. When using JSX, the children should be nested between the opening and closing tags. When not using JSX, the children should be passed as additional arguments to `React.createElement`. ## Rule Details Examples of **incorrect** code for this rule: ```jsx
} /> React.createElement("div", { children: 'Children' }) ``` Examples of **correct** code for this rule: ```jsx
Children
Children Child 1 Child 2 React.createElement("div", {}, 'Children') React.createElement("div", 'Child 1', 'Child 2') ``` ## Rule Options ```js "react/no-children-prop": [, { "allowFunctions": || false }] ``` ### `allowFunctions` When `true`, and passing a function as `children`, it must be in prop position and not child position. The following patterns are considered warnings: ```jsx {data => data.value} React.createElement(MyComponent, {}, data => data.value) ``` The following are **not** considered warnings: ```jsx data.value} /> React.createElement(MyComponent, { children: data => data.value }) ``` --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/no-danger-with-children.md # Disallow when a DOM element is using both children and dangerouslySetInnerHTML (`react/no-danger-with-children`) πŸ’Ό This rule is enabled in the β˜‘οΈ `recommended` [config](https://github.com/jsx-eslint/eslint-plugin-react/#shareable-configs). This rule helps prevent problems caused by using children and the dangerouslySetInnerHTML prop at the same time. React will throw a warning if this rule is ignored. ## Rule Details Examples of **incorrect** code for this rule: ```jsx
Children
Children ``` ```js React.createElement("div", { dangerouslySetInnerHTML: { __html: "HTML" } }, "Children"); React.createElement("Hello", { dangerouslySetInnerHTML: { __html: "HTML" } }, "Children"); ``` Examples of **correct** code for this rule: ```jsx
Children
Children ``` ```js React.createElement("div", { dangerouslySetInnerHTML: { __html: "HTML" } }); React.createElement("Hello", { dangerouslySetInnerHTML: { __html: "HTML" } }); React.createElement("div", {}, "Children"); React.createElement("Hello", {}, "Children"); ``` --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/no-danger.md # Disallow usage of dangerous JSX properties (`react/no-danger`) Dangerous properties in React are those whose behavior is known to be a common source of application vulnerabilities. The properties' names clearly indicate they are dangerous and should be avoided unless great care is taken. See ## Rule Details Examples of **incorrect** code for this rule: ```jsx var React = require('react'); var Hello =
; ``` Examples of **correct** code for this rule: ```jsx var React = require('react'); var Hello =
Hello World
; ``` ## Rule Options ```js ... "react/no-danger": [, { "customComponentNames": Array, }] ... ``` ### customComponentNames Defaults to `[]`, if you want to enable this rule for all custom components you can pass `customComponentNames` as `['*']`, or else you can pass specific components name to the array. ## When Not To Use It If you are certain the content passed to dangerouslySetInnerHTML is sanitized HTML you can disable this rule. --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/no-deprecated.md # Disallow usage of deprecated methods (`react/no-deprecated`) πŸ’Ό This rule is enabled in the β˜‘οΈ `recommended` [config](https://github.com/jsx-eslint/eslint-plugin-react/#shareable-configs). Several methods are deprecated between React versions. This rule will warn you if you try to use a deprecated method. Use the [shared settings](/README.md#configuration) to specify the React version. ## Rule Details Examples of **incorrect** code for this rule: ```jsx React.render(, root); React.unmountComponentAtNode(root); React.findDOMNode(this.refs.foo); React.renderToString(); React.renderToStaticMarkup(); React.createClass({ /* Class object */ }); const propTypes = { foo: PropTypes.bar, }; //Any factories under React.DOM React.DOM.div(); import React, { PropTypes } from 'react'; // old lifecycles (since React 16.9) componentWillMount() { } componentWillReceiveProps() { } componentWillUpdate() { } // React 18 deprecations import { render } from 'react-dom'; ReactDOM.render(
, container); import { hydrate } from 'react-dom'; ReactDOM.hydrate(
, container); import {unmountComponentAtNode} from 'react-dom'; ReactDOM.unmountComponentAtNode(container); import { renderToNodeStream } from 'react-dom/server'; ReactDOMServer.renderToNodeStream(element); ``` Examples of **correct** code for this rule: ```jsx // when React < 18 ReactDOM.render(, root); // when React is < 0.14 ReactDOM.findDOMNode(this.refs.foo); import { PropTypes } from 'prop-types'; UNSAFE_componentWillMount() { } UNSAFE_componentWillReceiveProps() { } UNSAFE_componentWillUpdate() { } ReactDOM.createPortal(child, container); import { createRoot } from 'react-dom/client'; const root = createRoot(container); root.unmount(); import { hydrateRoot } from 'react-dom/client'; const root = hydrateRoot(container, ); ``` --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/no-did-mount-set-state.md # Disallow usage of setState in componentDidMount (`react/no-did-mount-set-state`) Updating the state after a component mount will trigger a second `render()` call and can lead to property/layout thrashing. ## Rule Details This rule is aimed to forbid the use of `this.setState` in `componentDidMount` outside of functions, such as callbacks. Examples of **incorrect** code for this rule: ```jsx var Hello = createReactClass({ componentDidMount: function() { this.setState({ name: this.props.name.toUpperCase() }); }, render: function() { return
Hello {this.state.name}
; } }); ``` Examples of **correct** code for this rule: ```jsx var Hello = createReactClass({ componentDidMount: function() { this.onMount(function callback(newName) { this.setState({ name: newName }); }); }, render: function() { return
Hello {this.state.name}
; } }); ``` ```jsx var Hello = createReactClass({ componentDidMount: function() { this.props.onMount(); }, render: function() { return
Hello {this.props.name}
; } }); ``` ## Rule Options ```js ... "react/no-did-mount-set-state": [, ] ... ``` ### `disallow-in-func` mode By default this rule forbids any call to `this.setState` in `componentDidMount` outside of functions. The `disallow-in-func` mode makes this rule more strict by disallowing calls to `this.setState` even within functions. Examples of **incorrect** code for this rule: ```jsx var Hello = createReactClass({ componentDidMount: function() { this.setState({ name: this.props.name.toUpperCase() }); }, render: function() { return
Hello {this.state.name}
; } }); ``` ```jsx var Hello = createReactClass({ componentDidMount: function() { this.onMount(function callback(newName) { this.setState({ name: newName }); }); }, render: function() { return
Hello {this.state.name}
; } }); ``` --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/no-did-update-set-state.md # Disallow usage of setState in componentDidUpdate (`react/no-did-update-set-state`) Updating the state after a component update will trigger a second `render()` call and can lead to property/layout thrashing. ## Rule Details Examples of **incorrect** code for this rule: ```jsx var Hello = createReactClass({ componentDidUpdate: function() { this.setState({ name: this.props.name.toUpperCase() }); }, render: function() { return
Hello {this.state.name}
; } }); ``` Examples of **correct** code for this rule: ```jsx var Hello = createReactClass({ componentDidUpdate: function() { this.props.onUpdate(); }, render: function() { return
Hello {this.props.name}
; } }); ``` ```jsx var Hello = createReactClass({ componentDidUpdate: function() { this.onUpdate(function callback(newName) { this.setState({ name: newName }); }); }, render: function() { return
Hello {this.props.name}
; } }); ``` ## Rule Options ```js ... "react/no-did-update-set-state": [, ] ... ``` ### `disallow-in-func` mode By default this rule forbids any call to `this.setState` in `componentDidUpdate` outside of functions. The `disallow-in-func` mode makes this rule more strict by disallowing calls to `this.setState` even within functions. Examples of **incorrect** code for this rule: ```jsx var Hello = createReactClass({ componentDidUpdate: function() { this.setState({ name: this.props.name.toUpperCase() }); }, render: function() { return
Hello {this.state.name}
; } }); ``` ```jsx var Hello = createReactClass({ componentDidUpdate: function() { this.onUpdate(function callback(newName) { this.setState({ name: newName }); }); }, render: function() { return
Hello {this.state.name}
; } }); ``` --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/no-direct-mutation-state.md # Disallow direct mutation of this.state (`react/no-direct-mutation-state`) πŸ’Ό This rule is enabled in the β˜‘οΈ `recommended` [config](https://github.com/jsx-eslint/eslint-plugin-react/#shareable-configs). NEVER mutate `this.state` directly, as calling `setState()` afterwards may replace the mutation you made. Treat `this.state` as if it were immutable. The only place that's acceptable to assign this.state is in a ES6 `class` component constructor. ## Rule Details This rule is aimed to forbid the use of mutating `this.state` directly. Examples of **incorrect** code for this rule: ```jsx var Hello = createReactClass({ componentDidMount: function() { this.state.name = this.props.name.toUpperCase(); }, render: function() { return
Hello {this.state.name}
; } }); class Hello extends React.Component { constructor(props) { super(props) // Assign at instance creation time, not on a callback doSomethingAsync(() => { this.state = 'bad'; }); } } ``` Examples of **correct** code for this rule: ```jsx var Hello = createReactClass({ componentDidMount: function() { this.setState({ name: this.props.name.toUpperCase(); }); }, render: function() { return
Hello {this.state.name}
; } }); class Hello extends React.Component { constructor(props) { super(props) this.state = { foo: 'bar', } } } ``` --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/no-find-dom-node.md # Disallow usage of findDOMNode (`react/no-find-dom-node`) πŸ’Ό This rule is enabled in the β˜‘οΈ `recommended` [config](https://github.com/jsx-eslint/eslint-plugin-react/#shareable-configs). Facebook will eventually deprecate `findDOMNode` as it blocks certain improvements in React in the future. It is recommended to use callback refs instead. See [Dan Abramov comments and examples](https://github.com/jsx-eslint/eslint-plugin-react/issues/678#issue-165177220). ## Rule Details Examples of **incorrect** code for this rule: ```jsx class MyComponent extends Component { componentDidMount() { findDOMNode(this).scrollIntoView(); } render() { return
} } ``` Examples of **correct** code for this rule: ```jsx class MyComponent extends Component { componentDidMount() { this.node.scrollIntoView(); } render() { return
this.node = node} /> } } ``` --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/no-invalid-html-attribute.md # Disallow usage of invalid attributes (`react/no-invalid-html-attribute`) πŸ’‘ This rule is manually fixable by [editor suggestions](https://eslint.org/docs/latest/use/core-concepts#rule-suggestions). Some HTML elements have a specific set of valid values for some attributes. For instance the elements: `a`, `area`, `link`, or `form` all have an attribute called `rel`. There is a fixed list of values that have any meaning for this attribute on these tags (see [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/rel)). To help with minimizing confusion while reading code, only the appropriate values should be on each attribute. ## Rule Details This rule aims to remove invalid attribute values. ## Rule Options The options is a list of attributes to check. Defaults to `["rel"]`. ## When Not To Use It When you don't want to enforce attribute value correctness. --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/no-is-mounted.md # Disallow usage of isMounted (`react/no-is-mounted`) πŸ’Ό This rule is enabled in the β˜‘οΈ `recommended` [config](https://github.com/jsx-eslint/eslint-plugin-react/#shareable-configs). [`isMounted` is an anti-pattern][anti-pattern], is not available when using ES6 classes, and it is on its way to being officially deprecated. [anti-pattern]: https://legacy.reactjs.org/blog/2015/12/16/ismounted-antipattern.html ## Rule Details Examples of **incorrect** code for this rule: ```jsx var Hello = createReactClass({ handleClick: function() { setTimeout(function() { if (this.isMounted()) { return; } }); }, render: function() { return
Hello
; } }); ``` Examples of **correct** code for this rule: ```jsx var Hello = createReactClass({ render: function() { return
Hello
; } }); ``` --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/no-multi-comp.md # Disallow multiple component definition per file (`react/no-multi-comp`) Declaring only one component per file improves readability and reusability of components. ## Rule Details Examples of **incorrect** code for this rule: ```jsx var Hello = createReactClass({ render: function() { return
Hello {this.props.name}
; } }); var HelloJohn = createReactClass({ render: function() { return ; } }); ``` Examples of **correct** code for this rule: ```jsx var Hello = require('./components/Hello'); var HelloJohn = createReactClass({ render: function() { return ; } }); ``` ## Rule Options ```js ... "react/no-multi-comp": [, { "ignoreStateless": }] ... ``` ### `ignoreStateless` When `true` the rule will ignore stateless components and will allow you to have multiple stateless components, or one stateful component and some stateless components in the same file. Examples of **correct** code for this rule: ```jsx function Hello(props) { return
Hello {props.name}
; } function HelloAgain(props) { return
Hello again {props.name}
; } ``` ```jsx function Hello(props) { return
Hello {props.name}
; } class HelloJohn extends React.Component { render() { return ; } } module.exports = HelloJohn; ``` ## When Not To Use It If you prefer to declare multiple components per file you can disable this rule. --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/no-namespace.md # Enforce that namespaces are not used in React elements (`react/no-namespace`) Enforces the absence of a namespace in React elements, such as with `svg:circle`, as they are not supported in React. ## Rule Details The following patterns are considered warnings: ```jsx ``` ```jsx ``` The following patterns are **not** considered warnings: ```jsx ``` ```jsx ``` ## When Not To Use It If you are not using React. --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/no-object-type-as-default-prop.md # Disallow usage of referential-type variables as default param in functional component (`react/no-object-type-as-default-prop`) Warns if in a functional component, an object type value (such as array/object literal/function/etc) is used as default prop, to prevent potential unnecessary rerenders, and performance regressions. ## Rule Details Certain values (like arrays, objects, functions, etc) are compared by identity instead of by value. This means that, for example, whilst two empty arrays conceptually represent the same value - JavaScript semantics dictate that they are distinct and unequal as they represent two distinct values. When using object destructuring syntax you can set the default value for a given property if it does not exist. If you set the default value to one of the values that is compared by identity, it will mean that each time the destructure is evaluated the JS engine will create a new, distinct value in the destructured variable. In the context of a React functional component's props argument this means for each render, the property has a new, distinct value. When this value is passed to a hook as a dependency or passed into a child component as a property React will see this as a new value - meaning that a hook will be re-evaluated, or a memoized component will rerender. This obviously destroys any performance benefits you get from memoization. Additionally, in certain circumstances this can cause infinite rerender loops, which can often be hard to debug. It's worth noting that primitive literal values (`string`, `number`, `boolean`, `null`, and `undefined`) can be considered to be compared "by value", or alternatively, as always having the same identity (every `3` is the same exact `3`). Thus, it's safe for those to be inlined as a default value. To fix the violations, the easiest way is to use a referencing variable in module scope instead of using the literal values, e.g: ```jsx const emptyArray = []; function Component({ items = emptyArray, }) {} ``` Examples of ***invalid*** code for this rule: ```jsx function Component({ items = [], }) {} const Component = ({ items = {}, }) => {} const Component = ({ items = () => {}, }) => {} ``` Examples of ***valid*** code for this rule: ```jsx const emptyArray = []; function Component({ items = emptyArray, }) {} const emptyObject = {}; const Component = ({ items = emptyObject, }) => {} const noopFunc = () => {}; const Component = ({ items = noopFunc, }) => {} // primitives are all compared by value, so are safe to be inlined function Component({ num = 3, str = 'foo', bool = true, }) {} ``` --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/no-redundant-should-component-update.md # Disallow usage of shouldComponentUpdate when extending React.PureComponent (`react/no-redundant-should-component-update`) Warns if you have `shouldComponentUpdate` defined when defining a component that extends React.PureComponent. While having `shouldComponentUpdate` will still work, it becomes pointless to extend PureComponent. ## Rule Details Examples of **incorrect** code for this rule: ```jsx class Foo extends React.PureComponent { shouldComponentUpdate() { // do check } render() { return
Radical!
} } function Bar() { return class Baz extends React.PureComponent { shouldComponentUpdate() { // do check } render() { return
Groovy!
} } } ``` Examples of **correct** code for this rule: ```jsx class Foo extends React.Component { shouldComponentUpdate() { // do check } render() { return
Radical!
} } function Bar() { return class Baz extends React.Component { shouldComponentUpdate() { // do check } render() { return
Groovy!
} } } class Qux extends React.PureComponent { render() { return
Tubular!
} } ``` --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/no-render-return-value.md # Disallow usage of the return value of ReactDOM.render (`react/no-render-return-value`) πŸ’Ό This rule is enabled in the β˜‘οΈ `recommended` [config](https://github.com/jsx-eslint/eslint-plugin-react/#shareable-configs). > `ReactDOM.render()` currently returns a reference to the root `ReactComponent` instance. However, using this return value is legacy and should be avoided because future versions of React may render components asynchronously in some cases. If you need a reference to the root `ReactComponent` instance, the preferred solution is to attach a [callback ref](https://legacy.reactjs.org/docs/refs-and-the-dom.html#callback-refs) to the root element. Source: [ReactDOM documentation](https://legacy.reactjs.org/docs/react-dom.html#render) ## Rule Details This rule will warn you if you try to use the `ReactDOM.render()` return value. Examples of **incorrect** code for this rule: ```jsx const inst = ReactDOM.render(, document.body); doSomethingWithInst(inst); ``` Examples of **correct** code for this rule: ```jsx ReactDOM.render(, document.body); ReactDOM.render(, document.body, doSomethingWithInst); ``` --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/no-set-state.md # Disallow usage of setState (`react/no-set-state`) When using an architecture that separates your application state from your UI components (e.g. Flux), it may be desirable to forbid the use of local component state. This rule is especially helpful in read-only applications (that don't use forms), since local component state should rarely be necessary in such cases. ## Rule Details Examples of **incorrect** code for this rule: ```jsx var Hello = createReactClass({ getInitialState: function() { return { name: this.props.name }; }, handleClick: function() { this.setState({ name: this.props.name.toUpperCase() }); }, render: function() { return
Hello {this.state.name}
; } }); ``` Examples of **correct** code for this rule: ```jsx var Hello = createReactClass({ render: function() { return
Hello {this.props.name}
; } }); ``` --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/no-string-refs.md # Disallow using string references (`react/no-string-refs`) πŸ’Ό This rule is enabled in the β˜‘οΈ `recommended` [config](https://github.com/jsx-eslint/eslint-plugin-react/#shareable-configs). Currently, two ways are supported by React to refer to components. The first way, providing a string identifier, is now considered legacy in the official documentation. The documentation now prefers a second method -- referring to components by setting a property on the `this` object in the reference callback. ## Rule Details Examples of **incorrect** code for this rule: ```jsx var Hello = createReactClass({ render: function() { return
Hello, world.
; } }); ``` ```jsx var Hello = createReactClass({ componentDidMount: function() { var component = this.refs.hello; // ...do something with component }, render: function() { return
Hello, world.
; } }); ``` Examples of **correct** code for this rule: ```jsx var Hello = createReactClass({ componentDidMount: function() { var component = this.hello; // ...do something with component }, render() { return
{ this.hello = c; }}>Hello, world.
; } }); ``` ## Rule Options ```js "react/no-string-refs": [, {"noTemplateLiterals": }] ``` ### `noTemplateLiterals` When set to `true`, it will give warning when using template literals for refs. Examples of **incorrect** code for this rule: ```jsx var Hello = createReactClass({ render: function() { return
Hello, world.
; } }); ``` ```jsx var Hello = createReactClass({ render: function() { return
Hello, world.
; } }); ``` --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/no-this-in-sfc.md # Disallow `this` from being used in stateless functional components (`react/no-this-in-sfc`) In React, there are two styles of component. One is a class component: `class Foo extends React.Component {...}`, which accesses its props, context, and state as properties of `this`: `this.props.foo`, etc. The other are stateless functional components (SFCs): `function Foo(props, context) {...}`. As you can see, there's no `state` (hence the name - hooks do not change this), and the props and context are provided as its two functional arguments. In an SFC, state is usually best implements with a [React hook](https://reactjs.org/docs/hooks-overview.html) such as `React.useState()`. Attempting to access properties on `this` can sometimes be valid, but it's very commonly an error caused by unfamiliarity with the differences between the two styles of components, or a missed reference when converting a class component to an SFC. ## Rule Details Examples of **incorrect** code for this rule: ```jsx function Foo(props) { return (
{this.props.bar}
); } ``` ```jsx function Foo(props) { const { bar } = this.props; return (
{bar}
); } ``` ```jsx function Foo(props, context) { return (
{this.context.foo ? this.props.bar : ''}
); } ``` ```jsx function Foo(props, context) { const { foo } = this.context; const { bar } = this.props; return (
{foo ? bar : ''}
); } ``` ```jsx function Foo(props) { if (this.state.loading) { return ; } return (
{this.props.bar}
); } ``` ```jsx function Foo(props) { const { loading } = this.state; const { bar } = this.props; if (loading) { return ; } return (
{bar}
); } ``` Examples of **correct** code for this rule: ```jsx function Foo(props) { return (
{props.bar}
); } ``` ```jsx function Foo(props) { const { bar } = props; return (
{bar}
); } ``` ```jsx function Foo({ bar }) { return (
{bar}
); } ``` ```jsx function Foo(props, context) { return (
{context.foo ? props.bar : ''}
); } ``` ```jsx function Foo(props, context) { const { foo } = context; const { bar } = props; return (
{foo ? bar : ''}
); } ``` ```jsx function Foo({ bar }, { foo }) { return (
{foo ? bar : ''}
); } ``` --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/no-typos.md # Disallow common typos (`react/no-typos`) Ensure no casing typos were made declaring static class properties and lifecycle methods. Checks that declared `propTypes`, `contextTypes` and `childContextTypes` is supported by [react-props](https://github.com/facebook/prop-types) ## Rule Details This rule checks whether the declared static class properties and lifecycle methods related to React components do not contain any typos. It makes sure that the following class properties have no casing typos: - propTypes - contextTypes - childContextTypes - defaultProps and the following react lifecycle methods: - getDerivedStateFromProps - componentWillMount - UNSAFE_componentWillMount - componentDidMount - componentWillReceiveProps - UNSAFE_componentWillReceiveProps - shouldComponentUpdate - componentWillUpdate - UNSAFE_componentWillUpdate - getSnapshotBeforeUpdate - componentDidUpdate - componentDidCatch - componentWillUnmount - render Examples of **incorrect** code for this rule: ```js class MyComponent extends React.Component { static PropTypes = {} } class MyComponent extends React.Component { static proptypes = {} } class MyComponent extends React.Component { static ContextTypes = {} } class MyComponent extends React.Component { static contexttypes = {} } class MyComponent extends React.Component { static ChildContextTypes = {} } class MyComponent extends React.Component { static childcontexttypes = {} } class MyComponent extends React.Component { static DefaultProps = {} } class MyComponent extends React.Component { static defaultprops = {} } class MyComponent extends React.Component { componentwillMount() {} } class MyComponent extends React.Component { ComponentWillReceiveProps() {} } class MyComponent extends React.Component { componentdidupdate() {} } class MyComponent extends React.Component { static propTypes = { a: PropTypes.typo } } class MyComponent extends React.Component { getDerivedStateFromProps() {} } ``` Examples of **correct** code for this rule: ```js class MyComponent extends React.Component { static propTypes = {} } class MyComponent extends React.Component { static contextTypes = {} } class MyComponent extends React.Component { static childContextTypes = {} } class MyComponent extends React.Component { static defaultProps = {} } class MyComponent extends React.Component { componentWillMount() {} } class MyComponent extends React.Component { componentWillReceiveProps() {} } class MyComponent extends React.Component { componentDidUpdate() {} } class MyComponent extends React.Component { static propTypes = { a: PropTypes.bool.isRequired } } ``` --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/no-unescaped-entities.md # Disallow unescaped HTML entities from appearing in markup (`react/no-unescaped-entities`) πŸ’Ό This rule is enabled in the β˜‘οΈ `recommended` [config](https://github.com/jsx-eslint/eslint-plugin-react/#shareable-configs). πŸ’‘ This rule is manually fixable by [editor suggestions](https://eslint.org/docs/latest/use/core-concepts#rule-suggestions). This rule prevents characters that you may have meant as JSX escape characters from being accidentally injected as a text node in JSX statements. For example, if one were to misplace their closing `>` in a tag: ```jsx {/* oops! */} x="y"> Body Text ``` The body text of this would render as `x="y"> Body Text`, which is probably not what was intended. This rule requires that these special characters are escaped if they appear in the body of a tag. Another example is when one accidentally includes an extra closing brace. ```jsx {'Text'}} ``` The extra brace will be rendered, and the body text will be `Text}`. This rule will also check for `"` and `'`, which might be accidentally included when the closing `>` is in the wrong place. ```jsx {/* oops! */} c="d" Intended body text ``` The preferred way to include one of these characters is to use the HTML escape code. - `>` can be replaced with `>` - `"` can be replaced with `"`, `“`, `"` or `”` - `'` can be replaced with `'`, `‘`, `'` or `’` - `}` can be replaced with `}` Alternatively, you can include the literal character inside a subexpression (such as `
{'>'}
`. The characters `<` and `{` should also be escaped, but they are not checked by this rule because it is a syntax error to include those tokens inside of a tag. ## Rule Details Examples of **incorrect** code for this rule: ```jsx
>
``` Examples of **correct** code for this rule: ```jsx
>
``` ```jsx
{'>'}
``` ## Rule Options ```js ... "react/no-unescaped-entities": [, { "forbid": Array }] ... ``` ### `forbid` Overwrite the default forbidden entities array `['>', '"', '\'', '}']` with your own: ```js "react/no-unescaped-entities": ["error", {"forbid": [">", "}"]}], // or "react/no-unescaped-entities": ["error", {"forbid": [{ char: ">", alternatives: ['>'] }, { char: "}", alternatives: ['}'] }]}], ``` Where `char` is a special character and `alternatives` is the correct escapes. --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/no-unknown-property.md # Disallow usage of unknown DOM property (`react/no-unknown-property`) πŸ’Ό This rule is enabled in the β˜‘οΈ `recommended` [config](https://github.com/jsx-eslint/eslint-plugin-react/#shareable-configs). πŸ”§ This rule is automatically fixable by the [`--fix` CLI option](https://eslint.org/docs/latest/user-guide/command-line-interface#--fix). In JSX most DOM properties and attributes should be camelCased to be consistent with standard JavaScript style. This can be a possible source of error if you are used to writing plain HTML. Only `data-*` and `aria-*` attributes are usings hyphens and lowercase letters in JSX. ## Rule Details Examples of **incorrect** code for this rule: ```jsx var React = require('react'); var Hello =
Hello World
; var Alphabet =
Alphabet
; // Invalid aria-* attribute var IconButton =
; ``` Examples of **correct** code for this rule: ```jsx var React = require('react'); var Hello =
Hello World
; var Button = ; var Img = A cat sleeping on a keyboard; // aria-* attributes var IconButton = ; // data-* attributes var Data =
Some data
; // React components are ignored var MyComponent = ; var AnotherComponent = ; // Custom web components are ignored var MyElem =
; var AtomPanel = ; ``` ## Rule Options ```js ... "react/no-unknown-property": [, { ignore: , requireDataLowercase: }] ... ``` - `enabled`: for enabling the rule. 0=off, 1=warn, 2=error. Defaults to 0. - `ignore`: optional array of property and attribute names to ignore during validation. - `requireDataLowercase`: optional (default: `false`), require data-\* attributes to contain only lowercase characters. React will issue a warning when data-\* attributes contain uppercase characters. In order to catch such attributes, set the `requireDataLowercase` option to `true`. If you are using a library that passes something as a prop to JSX elements, it is recommended to add those props to the ignored properties. For example, if you use [emotion](https://emotion.sh/docs/introduction) and its [`css` prop](https://emotion.sh/docs/css-prop), add the following to your `.eslintrc` config file: ```js ... "react/no-unknown-property": ['error', { ignore: ['css'] }] ... ``` Now, the following code passes: ```jsx var StyledDiv =
; ``` ## When Not To Use It If you are not using JSX you can disable this rule. --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/no-unsafe.md # Disallow usage of unsafe lifecycle methods (`react/no-unsafe`) 🚫 This rule is _disabled_ in the β˜‘οΈ `recommended` [config](https://github.com/jsx-eslint/eslint-plugin-react/#shareable-configs). Certain legacy lifecycle methods are [unsafe for use in async React applications][async_rendering] and cause warnings in [_strict mode_][strict_mode]. These also happen to be the lifecycles that cause the most [confusion within the React community][component_lifecycle_changes]. [async_rendering]: https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html [strict_mode]: https://reactjs.org/docs/strict-mode.html#identifying-unsafe-lifecycles [component_lifecycle_changes]: https://reactjs.org/blog/2018/03/29/react-v-16-3.html#component-lifecycle-changes The rule checks the following methods: - `componentWillMount` (and `UNSAFE_componentWillMount` alias) - `componentWillReceiveProps` (and `UNSAFE_componentWillReceiveProps` alias) - `componentWillUpdate` (and `UNSAFE_componentWillUpdate` alias) ## Rule Details Examples of **incorrect** code for this rule: ```jsx class Foo extends React.Component { UNSAFE_componentWillMount() {} UNSAFE_componentWillReceiveProps() {} UNSAFE_componentWillUpdate() {} } ``` ```jsx const Foo = createReactClass({ UNSAFE_componentWillMount: function() {}, UNSAFE_componentWillReceiveProps: function() {}, UNSAFE_componentWillUpdate: function() {} }); ``` Examples of **correct** code for this rule: ```jsx class Foo extends Bar { UNSAFE_componentWillMount() {} UNSAFE_componentWillReceiveProps() {} UNSAFE_componentWillUpdate() {} } ``` ```jsx const Foo = bar({ UNSAFE_componentWillMount: function() {}, UNSAFE_componentWillReceiveProps: function() {}, UNSAFE_componentWillUpdate: function() {} }); ``` ## Rule Options ```json5 ... "react/no-unsafe": [, { "checkAliases": }] ... ``` ### `checkAliases` (default: `false`) When `true` the rule will also check aliases of unsafe methods: `componentWillMount`, `componentWillReceiveProps`, `componentWillUpdate`. Examples of **incorrect** code for this rule: ```jsx class Foo extends React.Component { componentWillMount() {} componentWillReceiveProps() {} componentWillUpdate() {} } ``` ```jsx const Foo = createReactClass({ componentWillMount: function() {}, componentWillReceiveProps: function() {}, componentWillUpdate: function() {} }); ``` Examples of **correct** code for this rule: ```jsx class Foo extends Bar { componentWillMount() {} componentWillReceiveProps() {} componentWillUpdate() {} } ``` ```jsx const Foo = bar({ componentWillMount: function() {}, componentWillReceiveProps: function() {}, componentWillUpdate: function() {} }); ``` --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/no-unstable-nested-components.md # Disallow creating unstable components inside components (`react/no-unstable-nested-components`) Creating components inside components (nested components) will cause React to throw away the state of those nested components on each re-render of their parent. React reconciliation performs element type comparison with [reference equality](https://reactjs.org/docs/reconciliation.html#elements-of-different-types). The reference to the same element changes on each re-render when defining components inside the render block. This leads to complete recreation of the current node and all its children. As a result the virtual DOM has to do extra unnecessary work and [possible bugs are introduced](https://codepen.io/ariperkkio/pen/vYLodLB). ## Rule Details The following patterns are considered warnings: ```jsx function Component() { function UnstableNestedComponent() { return
; } return (
); } ``` ```jsx function SomeComponent({ footer: Footer }) { return (
); } function Component() { return (
} />
); } ``` ```jsx class Component extends React.Component { render() { function UnstableNestedComponent() { return
; } return (
); } } ``` The following patterns are **not** considered warnings: ```jsx function OutsideDefinedComponent(props) { return
; } function Component() { return (
); } ``` ```jsx function Component() { return } />; } ``` ⚠️ WARNING ⚠️: Creating nested but memoized components is currently not detected by this rule but should also be avoided. If the `useCallback` or `useMemo` hook has no dependency, you can safely move the component definition out of the render function. If the hook does have dependencies, you should refactor the code so that you're able to move the component definition out of the render function. If you want React to throw away the state of the nested component, use a [`key`](https://reactjs.org/docs/lists-and-keys.html#keys) instead. ```jsx function Component() { // No ESLint warning but `MemoizedNestedComponent` should be moved outside of `Component`. const MemoizedNestedComponent = React.useCallback(() =>
, []); return (
); } ``` By default component creation is allowed inside component props only if prop name starts with `render`. See `allowAsProps` option for disabling this limitation completely. ```jsx function SomeComponent(props) { return
{props.renderFooter()}
; } function Component() { return (
} />
); } ``` ## Rule Options ```js ... "react/no-unstable-nested-components": [ "off" | "warn" | "error", { "allowAsProps": true | false, "customValidators": [] /* optional array of validators used for propTypes validation */ "propNamePattern": string } ] ... ``` You can allow component creation inside component props by setting `allowAsProps` option to true. When using this option make sure you are **calling** the props in the receiving component and not using them as elements. The following patterns are **not** considered warnings: ```jsx function SomeComponent(props) { return
{props.footer()}
; } function Component() { return (
} />
); } ``` You can allow other render prop naming conventions by setting the `propNamePattern` option. By default this option is `"render*"`. For example, if `propNamePattern` is set to `"*Renderer"` the following pattern is **not** considered warnings: ```jsx } /> ``` ## When Not To Use It If you are not interested in preventing bugs related to re-creation of the nested components or do not care about optimization of virtual DOM. --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/no-unused-class-component-methods.md # Disallow declaring unused methods of component class (`react/no-unused-class-component-methods`) Warns you if you have defined a method or property but it is never being used anywhere. ## Rule Details The following patterns are considered warnings: ```jsx class Foo extends React.Component { handleClick() {} render() { return null; } } ``` The following patterns are **not** considered warnings: ```jsx class Foo extends React.Component { static getDerivedStateFromError(error) { return { hasError: true }; } action() {} componentDidMount() { this.action(); } render() { return null; } } }); ``` --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/no-unused-prop-types.md # Disallow definitions of unused propTypes (`react/no-unused-prop-types`) Warns if a prop with a defined type isn't being used. > **Note**: You can provide types in runtime types using [PropTypes] and/or statically using [TypeScript] or [Flow]. This rule will validate your prop types regardless of how you define them. ## Rule Details Examples of **incorrect** code for this rule: ```jsx class Hello extends React.Component { render() { return
Hello Bob
; } } Hello.propTypes = { name: PropTypes.string }; ``` ```jsx type Props = { firstname: string; middlename: string; // middlename is never used by the Hello component lastname: string; } class Hello extends React.Component { render() { return
Hello {this.props.firstname} {this.props.lastname}
; } } ``` ```jsx type Props = { firstname: string; lastname: string; // lastname isn't used by the Hello component }; class Hello extends React.Component { render() { return
Hello {this.props.firstname}
; } } class Greetings extends React.Component { render() { return
Greetings {this.props.firstname} {this.props.lastname}
; } } ``` Examples of **correct** code for this rule: ```jsx class Hello extends React.Component { render() { return
Hello {this.props.name}
; } } Hello.propTypes = { name: PropTypes.string }; ``` ## Rule Options This rule can take one argument to ignore some specific props during validation. ```js ... "react/no-unused-prop-types": [, { ignore: , customValidators: , skipShapeProps: }] ... ``` - `enabled`: for enabling the rule. 0=off, 1=warn, 2=error. Defaults to 0. - `ignore`: optional array of props name to ignore during validation. - `customValidators`: optional array of validators used for propTypes validation. - `skipShapeProps`: In some cases it is impossible to accurately detect whether or not a `PropTypes.shape`'s values are being used. Setting this option to `true` will skip validation of `PropTypes.shape` (`true` by default). ## Known Issues/Limitations - [False Positives: SFC (helper render methods)](#false-positives-sfc) ### False Positives SFC Stateless Function Components (SFCs) accept props as an argument and return a JSX expression. Even if the function gets called from a component, the props that are only used inside the component are not be considered used by a component. Triggers false positive: ```js function AComponent(props) { function helperRenderer(aProp) { // is considered SFC return ( {aProp}{props.bProp} ); } return (
{helperRenderer(props.aProp)}
); } AComponent.propTypes = { aProp: PropTypes.string, bProp: PropTypes.string // bProp is defined but never used }; ``` A suggested fix is to assign a bProp to a variable outside of the SFC. ```js function AComponent(props) { const { bProp } = props function helperRenderer(aProp) { // is considered SFC return ( {aProp}{bProp} ); } return (
{helperRenderer(props.aProp)}
); } AComponent.propTypes = { aProp: PropTypes.string, bProp: PropTypes.string }; ``` [PropTypes]: https://reactjs.org/docs/typechecking-with-proptypes.html [TypeScript]: https://www.typescriptlang.org/ [Flow]: https://flow.org/ --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/no-unused-state.md # Disallow definitions of unused state (`react/no-unused-state`) Warns you if you have defined a property on the state, but it is not being used anywhere. ## Rule Details Examples of **incorrect** code for this rule: ```jsx class MyComponent extends React.Component { state = { foo: 0 }; render() { return ; } } var UnusedGetInitialStateTest = createReactClass({ getInitialState: function() { return { foo: 0 }; }, render: function() { return ; } }) ``` Examples of **correct** code for this rule: ```jsx class MyComponent extends React.Component { state = { foo: 0 }; render() { return ; } } var UnusedGetInitialStateTest = createReactClass({ getInitialState: function() { return { foo: 0 }; }, render: function() { return ; } }) ``` --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/no-will-update-set-state.md # Disallow usage of setState in componentWillUpdate (`react/no-will-update-set-state`) Updating the state during the componentWillUpdate step can lead to indeterminate component state and is not allowed. ## Rule Details Examples of **incorrect** code for this rule: ```jsx var Hello = createReactClass({ componentWillUpdate: function() { this.setState({ name: this.props.name.toUpperCase() }); }, render: function() { return
Hello {this.state.name}
; } }); ``` Examples of **correct** code for this rule: ```jsx var Hello = createReactClass({ componentWillUpdate: function() { this.props.prepareHandler(); }, render: function() { return
Hello {this.props.name}
; } }); ``` ```jsx var Hello = createReactClass({ componentWillUpdate: function() { this.prepareHandler(function callback(newName) { this.setState({ name: newName }); }); }, render: function() { return
Hello {this.props.name}
; } }); ``` ## Rule Options ```js ... "react/no-will-update-set-state": [, ] ... ``` ### `disallow-in-func` mode By default this rule forbids any call to `this.setState` in `componentWillUpdate` outside of functions. The `disallow-in-func` mode makes this rule more strict by disallowing calls to `this.setState` even within functions. Examples of **incorrect** code for this rule: ```jsx var Hello = createReactClass({ componentWillUpdate: function() { this.setState({ name: this.props.name.toUpperCase() }); }, render: function() { return
Hello {this.state.name}
; } }); ``` ```jsx var Hello = createReactClass({ componentWillUpdate: function() { this.prepareHandler(function callback(newName) { this.setState({ name: newName }); }); }, render: function() { return
Hello {this.state.name}
; } }); ``` --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/prefer-es6-class.md # Enforce ES5 or ES6 class for React Components (`react/prefer-es6-class`) React offers you two ways to create traditional components: using the ES5 `create-react-class` module or the new ES6 class system. ## Rule Details This rule allows you to enforce one way or another. ## Rule Options ```js ... "react/prefer-es6-class": [, ] ... ``` ### `always` mode Will enforce ES6 classes for React Components. This is the default mode. Examples of **incorrect** code for this rule: ```jsx var Hello = createReactClass({ render: function() { return
Hello {this.props.name}
; } }); ``` Examples of **correct** code for this rule: ```jsx class Hello extends React.Component { render() { return
Hello {this.props.name}
; } } ``` ### `never` mode Will enforce ES5 classes for React Components. Examples of **incorrect** code for this rule: ```jsx class Hello extends React.Component { render() { return
Hello {this.props.name}
; } } ``` Examples of **correct** code for this rule: ```jsx var Hello = createReactClass({ render: function() { return
Hello {this.props.name}
; } }); ``` --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/prefer-exact-props.md # Prefer exact proptype definitions (`react/prefer-exact-props`) Recommends options to ensure only exact prop definitions are used when writing components. This recommends solutions for PropTypes or for Flow types. In React, you can define prop types for components using propTypes. Such an example is below: ```jsx class Foo extends React.Component { render() { return

{this.props.bar}

; } } Foo.propTypes = { bar: PropTypes.string }; ``` The problem with this is that the consumer of the component could still pass in extra props. There could even be a typo for expected props. In order to prevent those situations, one could use the npm package [prop-types-exact](https://www.npmjs.com/package/prop-types-exact) to warn when unexpected props are passed to the component. One can also define props for a component using Flow types. Such an example is below: ```jsx class Foo extends React.Component { props: { bar: string } render() { return

{this.props.bar}

; } } ``` In this case, one could instead enforce only the exact props being used by using exact type objects, like below: ```jsx class Foo extends React.Component { props: {| bar: string |} render() { return

{this.props.bar}

; } } ``` See the [Flow docs](https://flow.org/en/docs/types/objects/#toc-exact-object-types) on exact object types for more information. ## Rule Details This rule will only produce errors for prop types when combined with the appropriate entries in `propWrapperFunctions`. For example: ```json { "settings": { "propWrapperFunctions": [ {"property": "exact", "exact": true} ] } } ``` The following patterns are considered warnings: ```jsx class Component extends React.Component { render() { return
; } } Component.propTypes = { foo: PropTypes.string }; ``` ```jsx class Component extends React.Component { static propTypes = { foo: PropTypes.string } render() { return
; } } ``` ```jsx class Component extends React.Component { props: { foo: string } render() { return
; } } ``` ```jsx function Component(props: { foo: string }) { return
; } ``` ```jsx type Props = { foo: string } function Component(props: Props) { return
; } ``` The following patterns are **not** considered warnings: ```jsx type Props = {| foo: string |} function Component(props: Props) { return
; } ``` ```jsx import exact from 'prop-types-exact'; class Component extends React.Component { render() { return
; } } Component.propTypes = exact({ foo: PropTypes.string }); ``` ## When Not To Use It If you aren't concerned about extra props being passed to a component or potential spelling errors for existing props aren't a common nuisance, then you can leave this rule off. --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/prefer-read-only-props.md # Enforce that props are read-only (`react/prefer-read-only-props`) πŸ”§ This rule is automatically fixable by the [`--fix` CLI option](https://eslint.org/docs/latest/user-guide/command-line-interface#--fix). Using Flow, one can define types for props. This rule enforces that prop types are read-only (covariant). ## Rule Details Examples of **incorrect** code for this rule: In Flow: ```jsx type Props = { name: string, } class Hello extends React.Component { render () { return
Hello {this.props.name}
; } } function Hello(props: {-name: string}) { return
Hello {props.name}
; } const Hello = (props: {|name: string|}) => (
Hello {props.name}
); ``` In TypeScript: ```tsx type Props = { name: string; } class Hello extends React.Component { render () { return
Hello {this.props.name}
; } } interface Props { name: string; } class Hello extends React.Component { render () { return
Hello {this.props.name}
; } } ``` Examples of **correct** code for this rule: In Flow: ```jsx type Props = { +name: string, } class Hello extends React.Component { render () { return
Hello {this.props.name}
; } } function Hello(props: {+name: string}) { return
Hello {props.name}
; } const Hello = (props: {|+name: string|}) => (
Hello {props.name}
); ``` In TypeScript: ```tsx type Props = { readonly name: string; } class Hello extends React.Component { render () { return
Hello {this.props.name}
; } } interface Props { readonly name: string; } class Hello extends React.Component { render () { return
Hello {this.props.name}
; } } ``` --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/prefer-stateless-function.md # Enforce stateless components to be written as a pure function (`react/prefer-stateless-function`) Stateless functional components are simpler than class based components and will benefit from future React performance optimizations specific to these components. ## Rule Details This rule will check your class based React components for - methods/properties other than `displayName`, `propTypes`, `contextTypes`, `defaultProps`, `render` and useless constructor (same detection as `eslint` [no-useless-constructor rule](https://eslint.org/docs/rules/no-useless-constructor)) - instance property other than `this.props` and `this.context` - extension of `React.PureComponent` (if the `ignorePureComponents` flag is true) - presence of `ref` attribute in JSX - the use of decorators - `render` method that return anything but JSX: `undefined`, `null`, etc. (only in React <15.0.0, see [shared settings](https://github.com/jsx-eslint/eslint-plugin-react/blob/master/README.md#configuration) for React version configuration) If none of these elements are found, the rule will warn you to write this component as a pure function. Examples of **incorrect** code for this rule: ```jsx var Hello = createReactClass({ render: function() { return
Hello {this.props.name}
; } }); ``` Examples of **correct** code for this rule: ```jsx const Foo = function(props, context) { const { location } = context.router; return
{props.foo}
; }; ``` Examples of **correct** code for this rule, in React <15.0.0: ```jsx class Foo extends React.Component { render() { if (!this.props.foo) { return null } return
{this.props.foo}
; } } ``` ## Rule Options ```js ... "react/prefer-stateless-function": [, { "ignorePureComponents": }] ... ``` - `enabled`: for enabling the rule. 0=off, 1=warn, 2=error. Defaults to 0. - `ignorePureComponents`: optional boolean set to `true` to ignore components extending from `React.PureComponent` (default to `false`). ### `ignorePureComponents` When `true` the rule will ignore Components extending from `React.PureComponent` that use `this.props` or `this.context`. Examples of **correct** code for this rule: ```jsx class Foo extends React.PureComponent { render() { return
{this.props.foo}
; } } class Bar extends React.PureComponent { render() { return
Baz
; } } ``` --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/prop-types.md # Disallow missing props validation in a React component definition (`react/prop-types`) πŸ’Ό This rule is enabled in the β˜‘οΈ `recommended` [config](https://github.com/jsx-eslint/eslint-plugin-react/#shareable-configs). Defining types for component props improves reusability of your components by validating received data. It can warn other developers if they make a mistake while reusing the component with improper data type. > **Note**: You can provide types in runtime types using [PropTypes] and/or statically using [TypeScript] or [Flow]. This rule will validate your prop types regardless of how you define them. ## Rule Details Examples of **incorrect** code for this rule: ```jsx function Hello({ name }) { return
Hello {name}
; // 'name' is missing in props validation } var Hello = createReactClass({ propTypes: { firstname: PropTypes.string.isRequired }, render: function() { return
Hello {this.props.firstname} {this.props.lastname}
; // 'lastname' type is missing in props validation } }); // Or in ES6 class Hello extends React.Component { render() { return
Hello {this.props.firstname} {this.props.lastname}
; // 'lastname' type is missing in props validation } } Hello.propTypes = { firstname: PropTypes.string.isRequired } ``` In TypeScript: ```tsx interface Props { age: number } function Hello({ name }: Props) { return
Hello {name}
; // 'name' type is missing in props validation } ``` Examples of **correct** code for this rule: ```jsx function Hello({ name }) { return
Hello {name}
; } Hello.propTypes = { name: PropTypes.string.isRequired } var Hello = createReactClass({ propTypes: { name: PropTypes.string.isRequired, }, render: function() { return
Hello {this.props.name}
; }, }); // Or in ES6: class HelloEs6 extends React.Component { render() { return
Hello {this.props.name}
; } } HelloEs6.propTypes = { name: PropTypes.string.isRequired, }; // ES6 + Public Class Fields (draft: https://tc39.github.io/proposal-class-public-fields/) class HelloEs6WithPublicClassField extends React.Component { static propTypes = { name: PropTypes.string.isRequired, } render() { return
Hello {this.props.name}
; } } ``` In TypeScript: ```tsx // destructured default prop values function Foo({ bar = "" }): JSX.Element { return
{bar}
; } function Foo({ bar = "" as string }): JSX.Element { return
{bar}
; } ``` In Flow: ```tsx type Props = { name: string } class Hello extends React.Component { render() { return
Hello {this.props.name}
; } } ``` Examples of **correct** code for this rule: ```jsx function Hello() { return
Hello World
; } // Referencing an external object disable the rule for the component function Hello({ name }) { return
Hello {name}
; } Hello.propTypes = myPropTypes; ``` ## Rule Options This rule can take one argument to ignore some specific props during validation. ```js ... "react/prop-types": [, { ignore: , customValidators: , skipUndeclared: }] ... ``` - `enabled`: for enabling the rule. 0=off, 1=warn, 2=error. Defaults to 0. - `ignore`: optional array of props name to ignore during validation. - `customValidators`: optional array of validators used for propTypes validation. - `skipUndeclared`: optional boolean to only error on components that have a propTypes block declared. ### As for "exceptions" It would seem that some common properties such as `props.children` or `props.className` (and alike) need to be treated as exceptions. As it aptly noticed in [#7](https://github.com/jsx-eslint/eslint-plugin-react/issues/7) > Why should children be an exception? > Most components don't need `this.props.children`, so that makes it extra important to document `children` in the prop types. Generally, you should use `PropTypes.node` or static type `React.Node` for `children`. It accepts anything that can be rendered: numbers, strings, elements or an array containing these types. Since 2.0.0 children is no longer ignored for props validation. ## About component detection For this rule to work we need to detect React components, this could be very hard since components could be declared in a lot of ways. For now we should detect components created with: - a function that return JSX or the result of a `React.createElement` call. - `createReactClass()` - an ES6 class that inherit from `React.Component` or `Component` [PropTypes]: https://reactjs.org/docs/typechecking-with-proptypes.html [TypeScript]: https://www.typescriptlang.org/ [Flow]: https://flow.org/ --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/react-in-jsx-scope.md # Disallow missing React when using JSX (`react/react-in-jsx-scope`) πŸ’ΌπŸš« This rule is enabled in the β˜‘οΈ `recommended` [config](https://github.com/jsx-eslint/eslint-plugin-react/#shareable-configs). This rule is _disabled_ in the πŸƒ `jsx-runtime` [config](https://github.com/jsx-eslint/eslint-plugin-react/#shareable-configs). When using JSX, `` expands to `React.createElement("a")`. Therefore the `React` variable must be in scope. If you are using the @jsx pragma this rule will check the designated variable and not the `React` one. ## Rule Details Examples of **incorrect** code for this rule: ```jsx var Hello =
Hello {this.props.name}
; ``` ```jsx /** @jsx Foo.bar */ var React = require('react'); var Hello =
Hello {this.props.name}
; ``` Examples of **correct** code for this rule: ```jsx import React from 'react'; var Hello =
Hello {this.props.name}
; ``` ```jsx var React = require('react'); var Hello =
Hello {this.props.name}
; ``` ```jsx /** @jsx Foo.bar */ var Foo = require('foo'); var Hello =
Hello {this.props.name}
; ``` ## When Not To Use It If you are not using JSX, or if you are setting `React` as a global variable. If you are using the [new JSX transform from React 17](https://reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html#removing-unused-react-imports), you should disable this rule by extending [`react/jsx-runtime`](https://github.com/jsx-eslint/eslint-plugin-react/blob/8cf47a8ac2242ee00ea36eac4b6ae51956ba4411/index.js#L165-L179) in your eslint config (add `"plugin:react/jsx-runtime"` to `"extends"`). --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/require-default-props.md # Enforce a defaultProps definition for every prop that is not a required prop (`react/require-default-props`) This rule aims to ensure that any non-required prop types of a component has a corresponding `defaultProps` value. > **Note**: You can provide types in runtime types using [PropTypes] and/or statically using [TypeScript] or [Flow]. This rule will validate your prop types regardless of how you define them. One advantage of `defaultProps` over custom default logic in your code is that `defaultProps` are resolved by React before the `PropTypes` typechecking happens, so typechecking will also apply to your `defaultProps`. The same also holds true for stateless functional components: default function parameters do not behave the same as `defaultProps` and thus using `defaultProps` is still preferred. To illustrate, consider the following example: With `defaultProps`: ```jsx const HelloWorld = ({ name }) => (

Hello, {name.first} {name.last}!

); HelloWorld.propTypes = { name: PropTypes.shape({ first: PropTypes.string, last: PropTypes.string, }) }; HelloWorld.defaultProps = { name: 'john' }; // Logs: // Invalid prop `name` of type `string` supplied to `HelloWorld`, expected `object`. ReactDOM.render(, document.getElementById('app')); ``` Without `defaultProps`: ```jsx const HelloWorld = ({ name = 'John Doe' }) => (

Hello, {name.first} {name.last}!

); HelloWorld.propTypes = { name: PropTypes.shape({ first: PropTypes.string, last: PropTypes.string, }) }; // Nothing is logged, renders: // "Hello,!" ReactDOM.render(, document.getElementById('app')); ``` ## Rule Details Examples of **incorrect** code for this rule: ```jsx function MyStatelessComponent({ foo, bar }) { return
{foo}{bar}
; } MyStatelessComponent.propTypes = { foo: PropTypes.string.isRequired, bar: PropTypes.string }; ``` ```jsx var Greeting = createReactClass({ render: function() { return
Hello {this.props.foo} {this.props.bar}
; }, propTypes: { foo: PropTypes.string, bar: PropTypes.string }, getDefaultProps: function() { return { foo: "foo" }; } }); ``` ```jsx class Greeting extends React.Component { render() { return (

Hello, {this.props.foo} {this.props.bar}

); } } Greeting.propTypes = { foo: PropTypes.string, bar: PropTypes.string }; Greeting.defaultProps = { foo: "foo" }; ``` ```jsx type Props = { foo: string, bar?: string }; function MyStatelessComponent(props: Props) { return
Hello {props.foo} {props.bar}
; } ``` Examples of **correct** code for this rule: ```jsx class Greeting extends React.Component { render() { return (

Hello, {this.props.foo} {this.props.bar}

); } static propTypes = { foo: PropTypes.string, bar: PropTypes.string.isRequired }; static defaultProps = { foo: "foo" }; } ``` ```jsx function MyStatelessComponent({ foo, bar }) { return
{foo}{bar}
; } MyStatelessComponent.propTypes = { foo: PropTypes.string.isRequired, bar: PropTypes.string.isRequired }; ``` ```jsx function MyStatelessComponent({ foo, bar }) { return
{foo}{bar}
; } MyStatelessComponent.propTypes = { foo: PropTypes.string.isRequired, bar: PropTypes.string }; MyStatelessComponent.defaultProps = { bar: 'some default' }; ``` ```jsx type Props = { foo: string, bar?: string }; function MyStatelessComponent(props: Props) { return
Hello {props.foo} {props.bar}
; } MyStatelessComponent.defaultProps = { bar: 'some default' }; ``` ```js function NotAComponent({ foo, bar }) {} NotAComponent.propTypes = { foo: PropTypes.string, bar: PropTypes.string.isRequired }; ``` ## Rule Options ```js ... "react/require-default-props": [, { "forbidDefaultForRequired": , "classes": "defaultProps" | "ignore", "functions": "defaultProps" | "defaultArguments" | "ignore" // @deprecated Use `functions` option instead. "ignoreFunctionalComponents": , }] ... ``` - `enabled`: for enabling the rule. 0=off, 1=warn, 2=error. Defaults to 0. - `forbidDefaultForRequired`: optional boolean to forbid prop default for a required prop. Defaults to false. - `classes`: optional string to determine which strategy a class component uses for defaulting props. Defaults to "defaultProps". - `functions`: optional string to determine which strategy a functional component uses for defaulting props. Defaults to "defaultProps". - `ignoreFunctionalComponents`: optional boolean to ignore this rule for functional components. Defaults to false. Deprecated, use `functions` instead. ### `forbidDefaultForRequired` Forbids setting a default for props that are marked as `isRequired`. Examples of **incorrect** code for this rule: ```jsx class Greeting extends React.Component { render() { return (

Hello, {this.props.foo} {this.props.bar}

); } static propTypes = { foo: PropTypes.string, bar: PropTypes.string.isRequired }; static defaultProps = { foo: "foo", bar: "bar" }; } ``` ```jsx function MyStatelessComponent({ foo, bar }) { return
{foo}{bar}
; } MyStatelessComponent.propTypes = { foo: PropTypes.string.isRequired, bar: PropTypes.string }; MyStatelessComponent.defaultProps = { foo: 'foo', bar: 'bar' }; ``` Examples of **correct** code for this rule: ```jsx class Greeting extends React.Component { render() { return (

Hello, {this.props.foo} {this.props.bar}

); } static propTypes = { foo: PropTypes.string, bar: PropTypes.string.isRequired }; static defaultProps = { foo: "foo" }; } ``` ```jsx function MyStatelessComponent({ foo, bar }) { return
{foo}{bar}
; } MyStatelessComponent.propTypes = { foo: PropTypes.string.isRequired, bar: PropTypes.string.isRequired }; ``` ### `classes` - "defaultProps": Use `.defaultProps`. It's default. - "ignore": Ignore this rule for class components. Examples of **incorrect** code for this rule, when set to `defaultProps`: ```jsx class Greeting extends React.Component { render() { return (

Hello, {this.props.foo} {this.props.bar}

); } static propTypes = { foo: PropTypes.string, bar: PropTypes.string.isRequired }; } ``` Examples of **correct** code for this rule, when set to `defaultProps`: ```jsx class Greeting extends React.Component { render() { return (

Hello, {this.props.foo} {this.props.bar}

); } static propTypes = { foo: PropTypes.string, bar: PropTypes.string.isRequired }; static defaultProps = { foo: "foo" }; } ``` ### `functions` - "defaultProps": Use `.defaultProps`. It's default. - "defaultArguments": Use default arguments in the function signature. - "ignore": Ignore this rule for functional components. Examples of **incorrect** code for this rule, when set to `defaultArguments`: ```jsx function Hello({ foo }) { return
{foo}
; } Hello.propTypes = { foo: PropTypes.string }; Hello.defaultProps = { foo: 'foo' } ``` ```jsx function Hello({ foo = 'foo' }) { return
{foo}
; } Hello.propTypes = { foo: PropTypes.string }; Hello.defaultProps = { foo: 'foo' } ``` ```jsx function Hello(props) { return
{props.foo}
; } Hello.propTypes = { foo: PropTypes.string }; ``` Examples of **correct** code for this rule, when set to `defaultArguments`: ```jsx function Hello({ foo = 'foo' }) { return
{foo}
; } Hello.propTypes = { foo: PropTypes.string }; ``` ```jsx function Hello({ foo }) { return
{foo}
; } Hello.propTypes = { foo: PropTypes.string.isRequired }; ``` ```jsx function Hello(props) { return
{props.foo}
; } Hello.propTypes = { foo: PropTypes.string.isRequired }; ``` ### `ignoreFunctionalComponents` When set to `true`, ignores this rule for all functional components. **Deprecated**, use `functions` instead. Examples of **incorrect** code for this rule: ```jsx class Greeting extends React.Component { render() { return (

Hello, {this.props.foo} {this.props.bar}

); } static propTypes = { foo: PropTypes.string, bar: PropTypes.string.isRequired }; static defaultProps = { foo: "foo", bar: "bar" }; } ``` Examples of **correct** code for this rule: ```jsx function MyStatelessComponent({ foo, bar }) { return
{foo}{bar}
; } MyStatelessComponent.propTypes = { foo: PropTypes.string, bar: PropTypes.string }; ``` ```jsx const MyStatelessComponent = ({ foo, bar }) => { return
{foo}{bar}
; } MyStatelessComponent.propTypes = { foo: PropTypes.string, bar: PropTypes.string }; ``` ```jsx const MyStatelessComponent = function({ foo, bar }) { return
{foo}{bar}
; } MyStatelessComponent.propTypes = { foo: PropTypes.string, bar: PropTypes.string }; ``` ## When Not To Use It If you don't care about using `defaultProps` for your component's props that are not required, you can disable this rule. ## Resources - [Official React documentation on defaultProps](https://legacy.reactjs.org/docs/typechecking-with-proptypes.html#default-prop-values) [PropTypes]: https://reactjs.org/docs/typechecking-with-proptypes.html [TypeScript]: https://www.typescriptlang.org/ [Flow]: https://flow.org/ --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/require-optimization.md # Enforce React components to have a shouldComponentUpdate method (`react/require-optimization`) This rule prevents you from creating React components without declaring a `shouldComponentUpdate` method. ## Rule Details Examples of **incorrect** code for this rule: ```js class YourComponent extends React.Component { } ``` ```js createReactClass({ }); ``` Examples of **correct** code for this rule: ```js class YourComponent extends React.Component { shouldComponentUpdate () { return false; } } ``` ```js createReactClass({ shouldComponentUpdate: function () { return false; } }); ``` ```js createReactClass({ mixins: [PureRenderMixin] }); ``` ```js @reactMixin.decorate(PureRenderMixin) createReactClass({ }); ``` ## Rule Options ```js ... "react/require-optimization": [, { allowDecorators: [] }] ... ``` - `enabled`: for enabling the rule. 0=off, 1=warn, 2=error. Defaults to 0. - `allowDecorators`: optional array of decorators names to allow validation. ### `allowDecorators` Sets the allowed names of decorators. If the variable is present in the chain of decorators, it validates Examples of **correct** code for this rule: ```js // ['pureRender'] @pureRender class Hello extends React.Component {} ``` ### Example ```js ... "react/require-optimization": [2, {allowDecorators: ['customDecorators']}] ... ``` --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/require-render-return.md # Enforce ES5 or ES6 class for returning value in render function (`react/require-render-return`) πŸ’Ό This rule is enabled in the β˜‘οΈ `recommended` [config](https://github.com/jsx-eslint/eslint-plugin-react/#shareable-configs). When writing the `render` method in a component it is easy to forget to return the JSX content. This rule will warn if the `return` statement is missing. ## Rule Details Examples of **incorrect** code for this rule: ```jsx var Hello = createReactClass({ render() {
Hello
; } }); class Hello extends React.Component { render() {
Hello
; } } ``` Examples of **correct** code for this rule: ```jsx var Hello = createReactClass({ render() { return
Hello
; } }); class Hello extends React.Component { render() { return
Hello
; } } ``` --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/self-closing-comp.md # Disallow extra closing tags for components without children (`react/self-closing-comp`) πŸ”§ This rule is automatically fixable by the [`--fix` CLI option](https://eslint.org/docs/latest/user-guide/command-line-interface#--fix). Components without children can be self-closed to avoid unnecessary extra closing tag. ## Rule Details Examples of **incorrect** code for this rule: ```jsx var HelloJohn = ; var HelloJohnCompound = ; ``` Examples of **correct** code for this rule: ```jsx var contentContainer =
; var intentionalSpace =
{' '}
; var HelloJohn = ; var HelloJohnCompound = ; var Profile = ; var ProfileCompound = ; var HelloSpace = {' '}; ``` ## Rule Options The rule can take one argument to select types of tags, which should be self-closed when this is possible. By default custom components tags and html tags should be self-closed. ```js ... "react/self-closing-comp": ["error", { "component": true, "html": true }] ... ``` ### `component` When `true`, custom components tags should be self-closed. Examples of **incorrect** code for this rule: ```jsx var HelloJohn = ; ``` Examples of **correct** code for this rule: ```jsx var contentContainer =
; var intentionalSpace =
{' '}
; var HelloJohn = ; var HelloJohnCompound = ; var Profile = ; var ProfileCompound = ; ``` ### `html` When `true`, html components tags should be self-closed. Examples of **incorrect** code for this rule: ```jsx var contentContainer =
; ``` Examples of **correct** code for this rule: ```jsx var contentContainer =
; var contentContainer =
; var intentionalSpace =
{' '}
; ``` --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/sort-comp.md # Enforce component methods order (`react/sort-comp`) πŸ”§ This rule is automatically fixable using the [`sort-comp` transform](https://github.com/reactjs/react-codemod/blob/master/transforms/sort-comp.js) in [react-codemod](https://www.npmjs.com/package/react-codemod). When creating React components it is more convenient to always follow the same organisation for method order to help you easily find lifecycle methods, event handlers, etc. ## Rule Details The default configuration ensures that the following order must be followed: 1. static methods and properties 2. lifecycle methods: `displayName`, `propTypes`, `contextTypes`, `childContextTypes`, `mixins`, `statics`, `defaultProps`, `constructor`, `getDefaultProps`, `state`, `getInitialState`, `getChildContext`, `getDerivedStateFromProps`, `componentWillMount`, `UNSAFE_componentWillMount`, `componentDidMount`, `componentWillReceiveProps`, `UNSAFE_componentWillReceiveProps`, `shouldComponentUpdate`, `componentWillUpdate`, `UNSAFE_componentWillUpdate`, `getSnapshotBeforeUpdate`, `componentDidUpdate`, `componentDidCatch`, `componentWillUnmount` (in this order). 3. custom methods 4. `render` method Examples of **incorrect** code for this rule: ```jsx var Hello = createReactClass({ render: function() { return
Hello
; }, displayName : 'Hello' }); ``` ```jsx class Hello extends React.Component { render() { return
Hello
; } static displayName = 'Hello'; } ``` Examples of **correct** code for this rule: ```jsx var Hello = createReactClass({ displayName : 'Hello', render: function() { return
Hello
; } }); ``` ```jsx class Hello extends React.Component { static displayName = 'Hello'; render() { return
Hello
; } } ``` ## Rule Options This rule can take one argument to customize the components organisation. ```js ... "react/sort-comp": [, { order: , groups: }] ... ``` - `enabled`: for enabling the rule. 0=off, 1=warn, 2=error. Defaults to 0. - `order`: optional array of methods to validate. - `groups`: optional object of methods groups. The default configuration is: ```js { order: [ 'static-methods', 'lifecycle', 'everything-else', 'render' ], groups: { lifecycle: [ 'displayName', 'propTypes', 'contextTypes', 'childContextTypes', 'mixins', 'statics', 'defaultProps', 'constructor', 'getDefaultProps', 'state', 'getInitialState', 'getChildContext', 'getDerivedStateFromProps', 'componentWillMount', 'UNSAFE_componentWillMount', 'componentDidMount', 'componentWillReceiveProps', 'UNSAFE_componentWillReceiveProps', 'shouldComponentUpdate', 'componentWillUpdate', 'UNSAFE_componentWillUpdate', 'getSnapshotBeforeUpdate', 'componentDidUpdate', 'componentDidCatch', 'componentWillUnmount' ] } } ``` - `static-variables` This group is not specified by default, but can be used to enforce class static variable positioning. - `static-methods` is a special keyword that refers to static class methods. - `lifecycle` refers to the `lifecycle` group defined in `groups`. - `everything-else` is a special group that matches all of the methods that do not match any of the other groups. - `render` refers to the `render` method. - `type-annotations`. This group is not specified by default, but can be used to enforce flow annotations' positioning. - `getters` This group is not specified by default, but can be used to enforce class getters' positioning. - `setters` This group is not specified by default, but can be used to enforce class setters' positioning. - `instance-variables` This group is not specified by default, but can be used to enforce all other instance variables' positioning. - `instance-methods` This group is not specified by default, but can be used to enforce all other instance methods' positioning. You can override this configuration to match your needs. For example, if you want to place your event handlers (`onClick`, `onSubmit`, etc.) before `render` but the other methods after it: ```js "react/sort-comp": [1, { order: [ 'static-methods', 'lifecycle', '/^on.+$/', 'render', 'everything-else' ] }] ``` Examples of **incorrect** code for this rule, with the above configuration: ```jsx var Hello = createReactClass({ render: function() { return
Hello
; }, onClick: function() {} }); ``` ```jsx class Hello extends React.Component { render() { return
Hello
; } onClick = this.onClick.bind(this); onClick() {} } ``` Examples of **correct** code for this rule, with the above configuration: ```jsx var Hello = createReactClass({ onClick: function() {}, render: function() { return
Hello
; } }); ``` ```jsx class Hello extends React.Component { onClick = this.onClick.bind(this); onClick() {} render() { return
Hello
; } } ``` If you want to split your `render` method into smaller ones and keep them just before render: ```js "react/sort-comp": [1, { order: [ 'static-methods', 'lifecycle', 'everything-else', 'rendering', ], groups: { rendering: [ '/^render.+$/', 'render' ] } }] ``` Examples of **incorrect** code for this rule, with the above configuration: ```jsx var Hello = createReactClass({ renderButton: function() {}, onClick: function() {}, render: function() { return
Hello
; } }); ``` ```jsx class Hello extends React.Component { renderButton = () => {} onClick = this.onClick.bind(this); onClick() {} render() { return
Hello
; } } ``` Examples of **correct** code for this rule, with the above configuration: ```jsx var Hello = createReactClass({ onClick: function() {}, renderButton: function() {}, render: function() { return
Hello
; } }); ``` ```jsx class Hello extends React.Component { onClick = this.onClick.bind(this); onClick() {} renderButton = () => {} render() { return
Hello
; } } ``` If you want to flow annotations to be at the top: ```js "react/sort-comp": [1, { order: [ 'type-annotations', 'static-methods', 'lifecycle', 'everything-else', 'render', ], }] ``` Examples of **incorrect** code for this rule, with the above configuration: ```jsx class Hello extends React.Component { onClick() { this._someElem = true; } props: Props; _someElem: bool; render() { return
Hello
; } } ``` Examples of **correct** code for this rule, with the above configuration: ```jsx type Props = {}; class Hello extends React.Component { props: Props; _someElem: bool; onClick() { this._someElem = true; } render() { return
Hello
; } } ``` ## When Not To Use It This rule is a formatting preference and not following it won't negatively affect the quality of your code. If components organisation isn't a part of your coding standards, then you can leave this rule off. --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/sort-default-props.md # Enforce defaultProps declarations alphabetical sorting (`react/sort-default-props`) Some developers prefer to sort `defaultProps` declarations alphabetically to be able to find necessary declarations easier at a later time. Others feel that it adds complexity and becomes a burden to maintain. ## Rule Details This rule checks all components and verifies that all `defaultProps` declarations are sorted alphabetically. A spread attribute resets the verification. The default configuration of the rule is case-sensitive. The following patterns are considered warnings: ```jsx var Component = createReactClass({ ... getDefaultProps: function() { return { z: "z", a: "a", b: "b" }; }, ... }); class Component extends React.Component { ... } Component.defaultProps = { z: "z", a: "a", b: "b" }; class Component extends React.Component { static defaultProps = { z: "z", y: "y", a: "a" } render() { return
; } } const Component = (props) => (...); Component.defaultProps = { z: "z", y: "y", a: "a" }; const defaults = { b: "b" }; const types = { a: PropTypes.string, b: PropTypes.string, c: PropTypes.string' }; function StatelessComponentWithSpreadInPropTypes({ a, b, c }) { return
{a}{b}{c}
; } StatelessComponentWithSpreadInPropTypes.propTypes = types; StatelessComponentWithSpreadInPropTypes.defaultProps = { c: "c", a: "a", ...defaults, }; export default class ClassWithSpreadInPropTypes extends BaseClass { static propTypes = { a: PropTypes.string, b: PropTypes.string, c: PropTypes.string, d: PropTypes.string, e: PropTypes.string, f: PropTypes.string } static defaultProps = { b: "b", a: "a", ...c.defaultProps, f: "f", e: "e", ...d.defaultProps } } ``` The following patterns are considered okay and do **not** cause warnings: ```jsx var Component = createReactClass({ ... getDefaultProps: function() { return { a: "a", b: "b", c: "c" }; }, ... }); class Component extends React.Component { ... } Component.defaultProps = { a: "a", b: "b", c: "c" }; class Component extends React.Component { static defaultProps = { a: PropTypes.any, b: PropTypes.any, c: PropTypes.any } render() { return
; } } const Component = (props) => (...); Component.defaultProps = { a: "a", y: "y", z: "z" }; const defaults = { b: "b" }; const types = { a: PropTypes.string, b: PropTypes.string, c: PropTypes.string' }; function StatelessComponentWithSpreadInPropTypes({ a, b, c }) { return
{a}{b}{c}
; } StatelessComponentWithSpreadInPropTypes.propTypes = types; StatelessComponentWithSpreadInPropTypes.defaultProps = { a: "a", c: "c", ...defaults, }; export default class ClassWithSpreadInPropTypes extends BaseClass { static propTypes = { a: PropTypes.string, b: PropTypes.string, c: PropTypes.string, d: PropTypes.string, e: PropTypes.string, f: PropTypes.string } static defaultProps = { a: "a", b: "b", ...c.defaultProps, e: "e", f: "f", ...d.defaultProps } } ``` ## Rule Options ```js ... "react/sort-default-props": [, { "ignoreCase": , }] ... ``` ### `ignoreCase` When `true` the rule ignores the case-sensitivity of the declarations order. ## When not to use This rule is a formatting preference and not following it won't negatively affect the quality of your code. If alphabetizing `defaultProps` declarations isn't a part of your coding standards, then you can leave this rule off. --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/sort-prop-types.md # Enforce propTypes declarations alphabetical sorting (`react/sort-prop-types`) πŸ”§ This rule is automatically fixable by the [`--fix` CLI option](https://eslint.org/docs/latest/user-guide/command-line-interface#--fix). πŸ”§ This rule is automatically fixable using the `--fix` [flag](https://eslint.org/docs/latest/user-guide/command-line-interface#--fix) on the command line. Some developers prefer to sort prop type declarations alphabetically to be able to find necessary declaration easier at the later time. Others feel that it adds complexity and becomes burden to maintain. ## Rule Details This rule checks all components and verifies that all propTypes declarations are sorted alphabetically. A spread attribute resets the verification. The default configuration of the rule is case-sensitive. Examples of **incorrect** code for this rule: ```jsx var Component = createReactClass({ propTypes: { z: PropTypes.number, a: PropTypes.any, b: PropTypes.string }, ... }); ``` ```jsx type Props = { z: number, a: any, b: string } class Component extends React.Component { ... } ``` ```jsx class Component extends React.Component { static propTypes = { z: PropTypes.any, y: PropTypes.any, a: PropTypes.any } render() { return
; } } ``` Examples of **correct** code for this rule: ```jsx var Component = createReactClass({ propTypes: { a: PropTypes.number, b: PropTypes.any, c: PropTypes.string }, ... }); ``` ```jsx type Props = { a: string, b: any, c: string, } class Component extends React.Component { ... } ``` ```jsx class Component extends React.Component { static propTypes = { a: PropTypes.any, b: PropTypes.any, c: PropTypes.any } render() { return
; } } ``` ## Rule Options ```js ... "react/sort-prop-types": [, { "callbacksLast": , "ignoreCase": , "requiredFirst": , "sortShapeProp": , "noSortAlphabetically": , "checkTypes": }] ... ``` ### `ignoreCase` When `true` the rule ignores the case-sensitivity of the declarations order. ### `callbacksLast` When `true`, propTypes for props beginning with "on" must be listed after all other props: ```js var Component = createReactClass({ propTypes: { a: PropTypes.number, z: PropTypes.string, onBar: PropTypes.func, onFoo: PropTypes.func, }, ... }); ``` ### `requiredFirst` When `true`, prop types for required props must be listed before all other props: ```js var Component = createReactClass({ propTypes: { barRequired: PropTypes.any.isRequired, fooRequired: PropTypes.any.isRequired, a: PropTypes.number, z: PropTypes.string, }, ... }); ``` ### `sortShapeProp` When `true`, props defined in `PropTypes.shape` must be sorted via the same rules as the top-level props: ```js var Component = createReactClass({ propTypes: { a: PropTypes.number, b: PropTypes.shape({ d: PropTypes.number, e: PropTypes.func, f: PropTypes.bool, }), c: PropTypes.string, }, ... }); ``` ### `noSortAlphabetically` When `true`, alphabetical order is not enforced: ```js var Component = createReactClass({ propTypes: { barRequired: PropTypes.any.isRequired, z: PropTypes.string, a: PropTypes.number, }, ... }); ``` ### `checkTypes` When `true`, the sorting of prop type definitions are checked. ## When Not To Use It This rule is a formatting preference and not following it won't negatively affect the quality of your code. If alphabetizing props declarations isn't a part of your coding standards, then you can leave this rule off. --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/state-in-constructor.md # Enforce class component state initialization style (`react/state-in-constructor`) ## Rule Details This rule will enforce the state initialization style to be either in a constructor or with a class property. ## Rule Options ```js ... "react/state-in-constructor": [, ] ... ``` ### `always` mode Will enforce the state initialization style to be in a constructor. This is the default mode. Examples of **incorrect** code for this rule: ```jsx class Foo extends React.Component { state = { bar: 0 } render() { return
Foo
} } ``` Examples of **correct** code for this rule: ```jsx class Foo extends React.Component { constructor(props) { super(props) this.state = { bar: 0 } } render() { return
Foo
} } ``` ### `never` mode Will enforce the state initialization style to be with a class property. Examples of **incorrect** code for this rule: ```jsx class Foo extends React.Component { constructor(props) { super(props) this.state = { bar: 0 } } render() { return
Foo
} } ``` Examples of **correct** code for this rule: ```jsx class Foo extends React.Component { state = { bar: 0 } render() { return
Foo
} } ``` ## When Not To Use It When the way a component state is being initialized doesn't matter. --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/static-property-placement.md # Enforces where React component static properties should be positioned (`react/static-property-placement`) This rule allows you to enforce where `childContextTypes`, `contextTypes`, `contextType`, `defaultProps`, `displayName`, and `propTypes` are declared in an ES6 class. ## Rule Details By default, this rule will check for and warn about declaring any of the above properties outside of the class body. The three key options are `static public field`, `static getter`, and `property assignment`. ### When `static public field` is enabled (default) Examples of **incorrect** code for this rule: ```js class MyComponent extends React.Component { static get childContextTypes() { /*...*/ } static get contextTypes() { /*...*/ } static get contextType() { /*...*/ } static get displayName() { /*...*/ } static get defaultProps() { /*...*/ } static get propTypes() { /*...*/ } } ``` ```js class MyComponent extends React.Component { /*...*/ } MyComponent.childContextTypes = { /*...*/ }; MyComponent.contextTypes = { /*...*/ }; MyComponent.contextType = { /*...*/ }; MyComponent.displayName = "Hello"; MyComponent.defaultProps = { /*...*/ }; MyComponent.propTypes = { /*...*/ }; ``` Examples of **correct** code for this rule: ```js class MyComponent extends React.Component { static childContextTypes = { /*...*/ }; static contextTypes = { /*...*/ }; static contextType = { /*...*/ }; static displayName = "Hello"; static defaultProps = { /*...*/ }; static propTypes = { /*...*/ }; } ``` ### When `static getter` is enabled Examples of **incorrect** code for this rule: ```js class MyComponent extends React.Component { static childContextTypes = { /*...*/ }; static contextTypes = { /*...*/ }; static contextType = { /*...*/ }; static displayName = "Hello"; static defaultProps = { /*...*/ }; static propTypes = { /*...*/ }; } ``` ```js class MyComponent extends React.Component { /*...*/ } MyComponent.childContextTypes = { /*...*/ }; MyComponent.contextTypes = { /*...*/ }; MyComponent.contextType = { /*...*/ }; MyComponent.displayName = "Hello"; MyComponent.defaultProps = { /*...*/ }; MyComponent.propTypes = { /*...*/ }; ``` Examples of **correct** code for this rule: ```js class MyComponent extends React.Component { static get childContextTypes() { /*...*/ } static get contextTypes() { /*...*/ } static get contextType() { /*...*/ } static get displayName() { /*...*/ } static get defaultProps() { /*...*/ } static get propTypes() { /*...*/ } } ``` ### When `property assignment` is enabled Examples of **incorrect** code for this rule: ```js class MyComponent extends React.Component { static childContextTypes = { /*...*/ }; static contextTypes = { /*...*/ }; static contextType = { /*...*/ }; static displayName = "Hello"; static defaultProps = { /*...*/ }; static propTypes = { /*...*/ }; } ``` ```js class MyComponent extends React.Component { static get childContextTypes() { /*...*/ } static get contextTypes() { /*...*/ } static get contextType() { /*...*/ } static get displayName() { /*...*/ } static get defaultProps() { /*...*/ } static get propTypes() { /*...*/ } } ``` Examples of **correct** code for this rule: ```js class MyComponent extends React.Component { /*...*/ } MyComponent.childContextTypes = { /*...*/ }; MyComponent.contextTypes = { /*...*/ }; MyComponent.contextType = { /*...*/ }; MyComponent.displayName = "Hello"; MyComponent.defaultProps = { /*...*/ }; MyComponent.propTypes = { /*...*/ }; ``` ## Rule Options ```json5 ... "react/static-property-placement": [] // `static public field` enabled ... ``` or alternatively: ```json5 ... "react/static-property-placement": [, ] ... ``` or alternatively: ```json5 ... "react/static-property-placement": [, , { childContextTypes: , contextTypes: , contextType: , defaultProps: , displayName: , propTypes: , }] ... ``` The `` value must be one these options: - `static public field` - `static getter` - `property assignment` The `options` schema defined above allows you to specify different rules for the different property fields available. ### Example configuration _This is only an example, we do not recommend this as a configuration._ ```json5 ... "react/static-property-placement": ["warn", "property assignment", { childContextTypes: "static getter", contextTypes: "static public field", contextType: "static public field", displayName: "static public field", }] ... ``` Based on the above configuration: - `defaultProps` and `propTypes` will both enforce the `property assignment` rule. - `childContextTypes` will enforce the `static getter` rule. - `contextTypes`, `contextType`, and `displayName` will enforce the `static public field` rule. ## When Not To Use It If you have no placement preference for React's static class properties. --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/style-prop-object.md # Enforce style prop value is an object (`react/style-prop-object`) Require that the value of the prop `style` be an object or a variable that is an object. ## Rule Details Examples of **incorrect** code for this rule: ```jsx
const styles = true;
``` ```js React.createElement("div", { style: "color: 'red'" }); React.createElement("div", { style: true }); React.createElement("Hello", { style: true }); const styles = true; React.createElement("div", { style: styles }); ``` Examples of **correct** code for this rule: ```jsx
const styles = { color: "red" };
``` ```js React.createElement("div", { style: { color: 'red' }}); React.createElement("Hello", { style: { color: 'red' }}); const styles = { height: '100px' }; React.createElement("div", { style: styles }); ``` ## Rule Options ```js ... "react/style-prop-object": [, { "allow": [] }] ... ``` ### `allow` A list of elements that are allowed to have a non-object value in their style attribute. The default value is `[]`. #### Example ```js { "allow": ["MyComponent"] } ``` Examples of **incorrect** code for this rule: ```js React.createElement(Hello, { style: "some styling" }); ``` Examples of **correct** code for this rule: ```js React.createElement(MyComponent, { style: "some styling" }); ``` --- # Source: https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/void-dom-elements-no-children.md # Disallow void DOM elements (e.g. ``, `
`) from receiving children (`react/void-dom-elements-no-children`) There are some HTML elements that are only self-closing (e.g. `img`, `br`, `hr`). These are collectively known as void DOM elements. If you try to give these children, React will give you a warning like: > Invariant Violation: img is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML`. ## Rule Details Examples of **incorrect** code for this rule: ```jsx
Children


React.createElement('br', undefined, 'Children') React.createElement('br', { children: 'Children' }) React.createElement('br', { dangerouslySetInnerHTML: { __html: 'HTML' } }) ``` Examples of **correct** code for this rule: ```jsx
Children
React.createElement('div', undefined, 'Children') React.createElement('div', { children: 'Children' }) React.createElement('div', { dangerouslySetInnerHTML: { __html: 'HTML' } }) ```