react/destructuring-assignment
Enforce one style for reading props, state, and context: destructured or not
Some components read props.name, and others destructure { name } first. With destructuring, the top of a component lists everything it uses. Without it, you always see where a value comes from. This rule makes your codebase stick to one style.
By default it asks for destructuring, in function components (props, context) and in class components (this.props, this.state, this.context).
--fix only works for destructureInSignature. It moves the destructuring into the parameter list.
Configure#
Off by default. To turn it on:
[lint.rules]
"react/destructuring-assignment" = "error" # or "warn"Every option, set to its default:
[lint.rules]
"react/destructuring-assignment" = [
"error",
"always", # "always" or "never"
{
ignoreClassFields = false,
destructureInSignature = "ignore", # "always" or "ignore"
},
]Examples#
function Badge(props) {
return <span className={props.colorMust use destructuring props assignment}>{props.labelMust use destructuring props assignment}</span>;
}class Counter extends React.Component {
render() {
return <output>{this.state.countMust use destructuring state assignment}</output>;
}
}function Badge({ color, label }) {
return <span className={color}>{label}</span>;
}
class Counter extends React.Component {
render() {
const { count } = this.state;
return <output>{count}</output>;
}
}Passing the whole object on is fine:
function Badge(props) {
return <span {...props} />;
}Options#
[lint.rules]
"react/destructuring-assignment" = ["error", "always", {
destructureInSignature = "always",
}]The first option is "always" (default) or "never". With "never", the rule reports destructuring instead:
"never"1 problemfunction Badge({ color, label }) {Must never use destructuring props assignment in SFC argument
return <span className={color}>{label}</span>;
}The second option is an object. Both keys only matter with "always":
| Option | Default | What it does |
|---|---|---|
ignoreClassFields | false | Allow this.props.x in a class field. |
destructureInSignature | "ignore" | "always" reports const { x } = props in the body of a function component, unless props is also used somewhere else. |
"always", { "ignoreClassFields": true }No problemsclass Counter extends React.Component {
state = { count: this.props.start };
render() {
const { count } = this.state;
return <output>{count}</output>;
}
}"always", { "destructureInSignature": "always" }1 problemfunction Badge(props) {
const { color, label } = propsMust destructure props in the function signature.;
return <span className={color}>{label}</span>;
}