Skip to content

Commit

Permalink
Merge pull request #1909 from alexandernanberg/fix/class-property-des…
Browse files Browse the repository at this point in the history
…tructure-assignment

Ignore class properties in destructuring-assignment
  • Loading branch information
ljharb committed Aug 5, 2018
2 parents 9dbb834 + 4382aa5 commit a466a77
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 3 deletions.
21 changes: 21 additions & 0 deletions docs/rules/destructuring-assignment.md
Expand Up @@ -85,3 +85,24 @@ const Foo = class extends React.PureComponent {
return <div>{this.state.title}</div>;
}
};
```

## Rule Options

```js
...
"react/destructuring-assignment": [<enabled>, "always", { "ignoreClassFields": <boolean> }]
...
```

### `ignoreClassFields`

When `true` the rule will ignore class field declarations.

The following patterns are then considered okay and do not cause warnings:

```jsx
class Foo extends React.PureComponent {
bar = this.props.bar
}
```
20 changes: 17 additions & 3 deletions lib/rules/destructuring-assignment.js
Expand Up @@ -22,12 +22,20 @@ module.exports = {
'always',
'never'
]
}, {
type: 'object',
properties: {
ignoreClassFields: {
type: 'boolean'
}
},
additionalProperties: false
}]
},

create: Components.detect((context, components, utils) => {
const configuration = context.options[0] || DEFAULT_OPTION;

const ignoreClassFields = context.options[1] && context.options[1].ignoreClassFields === true || false;

/**
* Checks if a prop is being assigned a value props.bar = 'bar'
Expand Down Expand Up @@ -82,7 +90,10 @@ module.exports = {
!isAssignmentToProp(node)
);

if (isPropUsed && configuration === 'always') {
if (
isPropUsed && configuration === 'always' &&
!(ignoreClassFields && node.parent.type === 'ClassProperty')
) {
context.report({
node: node,
message: `Must use destructuring ${node.object.property.name} assignment`
Expand Down Expand Up @@ -128,7 +139,10 @@ module.exports = {
});
}

if (classComponent && destructuringClass && configuration === 'never') {
if (
classComponent && destructuringClass && configuration === 'never' &&
!(ignoreClassFields && node.parent.type === 'ClassProperty')
) {
context.report({
node: node,
message: `Must never use destructuring ${node.init.property.name} assignment`
Expand Down
8 changes: 8 additions & 0 deletions tests/lib/rules/destructuring-assignment.js
Expand Up @@ -165,6 +165,14 @@ ruleTester.run('destructuring-assignment', rule, {
}
}
`
}, {
code: `
class Foo extends React.Component {
bar = this.props.bar
}
`,
options: ['always', {ignoreClassFields: true}],
parser: 'babel-eslint'
}],

invalid: [{
Expand Down

0 comments on commit a466a77

Please sign in to comment.