Skip to content
This repository has been archived by the owner on Aug 18, 2020. It is now read-only.

Add react-prefer-private-members rule #95

Merged
merged 4 commits into from
Jun 4, 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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

### Added
* `shopify/prefer-pascal-case-enums` ([#96](https://github.com/Shopify/eslint-plugin-shopify/pull/96))
* `shopify/react-prefer-private-members` ([#95](https://github.com/Shopify/eslint-plugin-shopify/pull/95))

## [22.0.0]
* Updated dependencies
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,7 @@ This plugin provides the following custom rules, which are included as appropria
- [prefer-pascal-case-enums](docs/rules/prefer-pascal-case-enums.md): Prefer TypeScript enums be defined using pascal case.
- [prefer-twine](docs/rules/prefer-twine.md): Prefer Twine over Bindings as the name for twine imports.
- [react-initialize-state](docs/rules/react-initialize-state.md): Require that React component state be initialized when it has a non-empty type.
- [react-prefer-private-members](docs/rules/react-prefer-private-members.md): Prefer all non-React-specific members be marked private in React class components.
- [react-type-state](docs/rules/react-type-state.md): Require that React component state be typed in TypeScript.
- [restrict-full-import](docs/rules/restrict-full-import.md): Prevent importing the entirety of a package.
- [sinon-no-restricted-features](docs/rules/sinon-no-restricted-features.md): Restrict the use of specified sinon features.
Expand Down
64 changes: 64 additions & 0 deletions docs/rules/react-prefer-private-members.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
# Disallow public members within React component classes (react-prefer-private-members)

This rule enforces all non-React-specific members be marked private in React class components.

## Rule Details

When a member of class is marked private, it cannot be accessed from outside of its containing class. This restriction is prefered when writing React components, where encapsulation is almost always desireable.

The following patterns are considered warnings:

```ts
class MyComponent extends React.Component<Props, State> {
publicMethod() {}
alsoPublic: string;
}
```

The following patterns are not warnings:
```ts
class MyComponent extends React.Component<Props, State> {
private publicMethod() {}
private alsoPublic: string;
}
```

The Lifecycle methods and static properties that are part of the React API are not required to be private for this rule.

```ts
class MyComponent extends React.Component<Props, State> {
private publicMethod() {}
private alsoPublic: string;
static propTypes = {}
static defaultProps = {}
static childContextTypes = {}
static contextTypes = {}
getDerivedStateFromProps() {}
componentWillMount() {}
UNSAFE_componentWillMount() {}
componentDidMount() {}
componentWillReceiveProps() {}
UNSAFE_componentWillReceiveProps() {}
shouldComponentUpdate() {}
componentWillUpdate() {}
UNSAFE_componentWillUpdate() {}
getSnapshotBeforeUpdate() {}
componentDidUpdate() {}
componentDidCatch() {}
componentWillUnmount() {}
render() {}
}
```

Exposing subcomponents as public static members is not considered a warning for this rule.

```ts
class MyComponent extends React.Component<Props, State> {
static MySubComponent = MySubComponent;
render() {}
}
```

## When Not To Use It

If you do not want to restrict public members on React class components, you can safely disable this rule.
93 changes: 93 additions & 0 deletions lib/rules/react-prefer-private-members.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
const pascalCase = require('pascal-case');
const Components = require('eslint-plugin-react/lib/util/Components');

module.exports = {
meta: {
docs: {
description: 'Disallow public members within React component classes',
category: 'Best Practices',
recommended: true,
uri:
'https://github.com/Shopify/eslint-plugin-shopify/blob/master/docs/rules/react-prefer-private-members.md',
},
},

create: Components.detect((context, components, utils) => {
let isES6Component = false;
let componentName = null;

function report({node, componentName: classComponent}) {
const {
key: {name},
} = node;

context.report({
node,
message: `'{{name}}' should be a private member of '{{classComponent}}'.`,
data: {name, classComponent},
});
}

return {
ClassDeclaration(node) {
isES6Component = utils.isES6Component(node);
componentName = node.id.name;
},
ClassProperty(node) {
if (!isES6Component || isValid(node)) {
return;
}

report({node, componentName});
},
MethodDefinition(node) {
if (!isES6Component || isValid(node)) {
return;
}

report({node, componentName});
},
};
}),
};

function isValid(node) {
return (
node.accessibility === 'private' ||
isReactLifeCycleMethod(node) ||
isReactStaticProperty(node) ||
isCompoundComponentMember(node)
);
}

function isReactLifeCycleMethod({key: {name}}) {
return [
'getDerivedStateFromProps',
'componentWillMount',
'UNSAFE_componentWillMount',
'componentDidMount',
'componentWillReceiveProps',
'UNSAFE_componentWillReceiveProps',
'shouldComponentUpdate',
'componentWillUpdate',
'UNSAFE_componentWillUpdate',
'getSnapshotBeforeUpdate',
'componentDidUpdate',
'componentDidCatch',
'componentWillUnmount',
'render',
].some((method) => method === name);
}

function isReactStaticProperty({key: {name}}) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think you probably want to allow all static properties, or at least those that are pascal-case, to allow for our (pretty common) pattern of exposing subcomponent as public static members.

return [
'propTypes',
'contextTypes',
'childContextTypes',
'defaultProps',
].some((method) => method === name);
}

function isCompoundComponentMember({key: {name}}) {
return name === pascalCase(name);
}
139 changes: 139 additions & 0 deletions tests/lib/rules/react-prefer-private-members.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
const {RuleTester} = require('eslint');
const rule = require('../../../lib/rules/react-prefer-private-members');

const ruleTester = new RuleTester();

require('babel-eslint');
require('typescript-eslint-parser');

const babelParser = 'babel-eslint';
const typeScriptParser = 'typescript-eslint-parser';

function makeError({type = 'ClassProperty', memberName, componentName}) {
return {
type,
message: `'${memberName}' should be a private member of '${componentName}'.`,
};
}

ruleTester.run('react-prefer-private-members', rule, {
valid: [
{
code: `class Button extends React.Component {
private member = true;
componentDidMount() {}
}`,
parser: typeScriptParser,
},
{
code: `class Button extends Klass {
publicMember = true
publicMethod() {}
}`,
parser: babelParser,
},
{
code: 'class Button extends React.Component {}',
parser: babelParser,
},
{
code: `class KitchenSink extends React.Component {
static propTypes = {}
static defaultProps = {}
static childContextTypes = {}
static contextTypes = {}
getDerivedStateFromProps() {}
componentWillMount() {}
UNSAFE_componentWillMount() {}
componentDidMount() {}
componentWillReceiveProps() {}
UNSAFE_componentWillReceiveProps() {}
shouldComponentUpdate() {}
componentWillUpdate() {}
UNSAFE_componentWillUpdate() {}
getSnapshotBeforeUpdate() {}
componentDidUpdate() {}
componentDidCatch() {}
componentWillUnmount() {}
render() {}
}`,
parser: babelParser,
},
{
code: `class CompoundComponent extends React.Component {
static propTypes = {}
static Item = Item
static AnotherItem = AnotherItem
render() {}
}`,
parser: babelParser,
},
],
invalid: [
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Need more tests than this (missing for private members, static members, etc

{
code: `class Button extends React.Component {
publicMember = true;
componentDidMount() {}
}`,
parser: babelParser,
errors: [
makeError({memberName: 'publicMember', componentName: 'Button'}),
],
},
{
code: `class Button extends React.Component {
static Valid = Valid;
static inValid = inValid;
render() {}
}`,
parser: babelParser,
errors: [makeError({memberName: 'inValid', componentName: 'Button'})],
},
{
code: `class Button extends React.Component {
private validMember: string;
private alsoValidMember() {};
inValid: string;
alsoInvalid() {}
render() {}
}`,
parser: typeScriptParser,
errors: [
makeError({memberName: 'inValid', componentName: 'Button'}),
makeError({
type: 'MethodDefinition',
memberName: 'alsoInvalid',
componentName: 'Button',
}),
],
},
{
code: `class Button extends React.Component {
publicMethod() {}
componentDidMount() {}
}`,
parser: babelParser,
errors: [
makeError({
type: 'MethodDefinition',
memberName: 'publicMethod',
componentName: 'Button',
}),
],
},
{
code: `class PureButton extends React.PureComponent {
publicMethod() {}
componentDidMount() {}
}`,
parser: babelParser,
errors: [
makeError({
type: 'MethodDefinition',
memberName: 'publicMethod',
componentName: 'PureButton',
}),
],
},
],
});