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 = Cannot click me ;
var Img = ;
// aria-* attributes
var IconButton = {closeIcon} ;
// 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' } })
```