Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ignore class properties in destructuring-assignment #1909

Merged
merged 1 commit into from Aug 5, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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