Giter Site home page Giter Site logo

palantir / tslint-react Goto Github PK

View Code? Open in Web Editor NEW
751.0 257.0 80.0 222 KB

:orange_book: Lint rules related to React & JSX for TSLint.

License: Apache License 2.0

Shell 0.77% TypeScript 93.99% JavaScript 5.24%
tslint linting-rules react jsx typescript octo-correct-managed

tslint-react's Introduction

NPM version Downloads Circle CI

tslint-react

Lint rules related to React & JSX for TSLint.

Usage

tslint-react has peer dependencies on TSLint and TypeScript.

To use these lint rules with the default preset, use configuration inheritance via the extends keyword. Here's a sample configuration where tslint.json lives adjacent to your node_modules folder:

{
  "extends": ["tslint:latest", "tslint-react"],
  "rules": {
    // override tslint-react rules here
    "jsx-wrap-multiline": false
  }
}

To lint your .ts and .tsx files you can simply run tslint -c tslint.json 'src/**/*.{ts,tsx}'.

Semantic versioning

The built-in configuration preset you get with "extends": "tslint-react" is semantically versioned in a manner similar to TSLint's built-in presets and the TypeScript language itself. As new rules are added to tslint-react across minor versions, stricter checks may be enabled here. Your code is not guaranteed to continue passing checks across these version bumps. If you wish to ensure that npm upgrade or yarn upgrade never breaks your build, declare a tilde dependency on this package (e.g. "~1.0.0").

Rules

  • jsx-alignment
    • Enforces a consistent style for multiline JSX elements which promotes ease of editing via line-wise manipulations as well as maintainability via small diffs when changes are made.
    // Good:
    const element = <div
        className="foo"
        tabIndex={1}
    >
        {children}
    </div>;
    
    // Also Good:
    <Button
        appearance="pretty"
        disabled
        label="Click Me"
        size={size}
    />
  • jsx-ban-elements (since v3.4.0)
    • Allows blacklisting of JSX elements with an optional explanatory message in the reported failure.
  • jsx-ban-props (since v2.3.0)
    • Allows blacklisting of props in JSX with an optional explanatory message in the reported failure.
  • jsx-boolean-value (since v2.5.0)
    • When using a boolean attribute in JSX, you can set the attribute value to true or omit the value. This rule will enforce one or the other to keep consistency in your code.
    • Rule options: ["always", "never"]
    • Default is set to always.
  • jsx-curly-spacing (since v1.1.0)
    • Requires or bans spaces between curly brace characters in JSX.
    • Rule options: ["always", "never"]
    • Includes automatic code fix
  • jsx-equals-spacing (since v3.2.0)
    • Requires or bans spaces before and after the = token in JSX element attributes.
    • Rule options: ["always", "never"]
    • Includes automatic code fix
  • jsx-key (since v3.2.0)
    • Warns for missing key props in JSX element array literals and inside return statements of Array.prototype.map callbacks.
      • N.B. This rule only does a simple check for .map(...) syntax and does not inspect computed types of expressions. As such, it may produce false positives if you use APIs that look similar to .map().
    • Rule options: none
  • jsx-no-bind (since v2.6.0)
    • Forbids function binding in JSX attributes. This has the same intent as jsx-no-lambda in helping you avoid excessive re-renders.
    • Note that this currently only does a simple syntactic check, not a semantic one (it doesn't use the type checker). So it may have some rare false positives if you define your own .bind function and supply this as a parameter.
    • Rule options: none
  • jsx-no-lambda
    • Creating new anonymous functions (with either the function syntax or ES2015 arrow syntax) inside the render call stack works against pure component rendering. When doing an equality check between two lambdas, React will always consider them unequal values and force the component to re-render more often than necessary.
    • Rule options: none
  • jsx-no-multiline-js
    • Disallows multiline JS expressions inside JSX blocks to promote readability
    • Rule options: none
  • jsx-no-string-ref
    • Passing strings to the ref prop of React elements is considered a legacy feature and will soon be deprecated. Instead, use a callback.
    • Rule options: none
  • jsx-use-translation-function (since v2.4.0)
    • Enforces use of a translation function. Plain string literals are disallowed in JSX when enabled.
    • Rule options: ["allow-punctuation", "allow-htmlentities"]
    • Off by default
  • jsx-self-close (since v0.4.0)
    • Enforces that JSX elements with no children are self-closing.
    • Includes automatic code fix
    // bad
    <div className="foo"></div>
    // good
    <div className="foo" />
    • Rule options: none
  • jsx-space-before-trailing-slash
    • Checks that self-closing JSX elements have a space before the '/>' part.
    • Rule options: none
    • Includes automatic code fix
  • jsx-wrap-multiline (since v2.1)
    • Enforces that multiline JSX expressions are wrapped with parentheses.
    • Opening parenthesis must be followed by a newline.
    • Closing parenthesis must be preceded by a newline.
    // bad
    const button = <button type="submit">
        Submit
    </button>;
    // good
    const button = (
        <button type="submit">
            Submit
        </button>
    );

Development

We track rule suggestions on Github issues -- here's a useful link to view all the current suggestions. Tickets are roughly triaged by priority (P1, P2, P3).

We're happy to accept PRs for new rules, especially those marked as Status: Accepting PRs. If submitting a PR, try to follow the same style conventions as the core TSLint project.

Quick Start (requires Node v6+, yarn v0.22+):

  1. yarn
  2. yarn verify
  3. yarn lint

Changelog

See the Github release history.

tslint-react's People

Contributors

adidahiya avatar andrewhathaway avatar bolatovumar avatar bookman25 avatar cheezery avatar davidlipo avatar dmiller9911 avatar dryganets avatar enoshixi avatar heatherbooker avatar illusionmh avatar ismail-syed avatar jaredpalmer avatar jeffwillette avatar jkillian avatar jomasti avatar longlho avatar lukyth avatar lvillani avatar markwongsk avatar mdibyo avatar mohsen1 avatar nmiyake avatar no23reason avatar nwolverson avatar olafmerkert avatar praxxis avatar quentinbouygues avatar suchanlee avatar tanmoyopenroot avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

tslint-react's Issues

New Rule: component-destructure-props

Enforces destructuring of this.props fields inside rendering methods in a component class to encourage succinctness.

good:

public render() {
  const { foo, bar } = this.props;
  return <SomeComponent foo={bar} bar={foo} />;
}

bad:

public render() {
  return <SomeComponent foo={this.props.bar} bar={this.props.foo} />;
}

Destructuring also allows you to address conflicts with other identifiers in scope:

const foo: string;

public render() {
  const { foo: awesomeFoo, bar } = this.props;
  return <SomeComponent foo={bar} bar={awesomeFoo} />;
}

jsx-wrap-multiline false positives

I think the case below should not cause error:

https://github.com/ant-design/ant-design-mobile/blob/master/components/accordion/demo/basic.tsx#L13

components/accordion/demo/basic.tsx[13, 9]: Multiline JSX elements must be wrapped in parentheses
// bad
const button = <button type="submit">
    Submit
</button>;
// good
const button = (
    <button type="submit">
        Submit
    </button>
);

// why this is bad ? any reason we need wrap inner button with parentheses?
const button = (
   <div>
       <button type="submit">
          Submit
      </button>
   <div>
);

Provide presets comparable to tslint:latest / tslint:recommended

Please correct me if I'm wrong, but currently one has to enable rules manually.

Would it instead please be possible to provide presets comparable to tslint:latest / tslint:recommended so one doesn't have to keep track of the current set of rules?

Reasoning would be the same as with TSLint - as in I don't want to argue / worry about code style but simply get the currently established best practice.

New Rule: jsx-alignment

Enforce this alignment when tags span multiple lines:

<input
    type="search"
    placeholder="Search..."
/>

New rule: react-no-set-state-in-update-lifecycle

There are a couple places I'd like to ban this.setState in component lifecycle methods:

1. in componentWillUpdate

Doing this can lead to infinite recursion.

2. in componentDidUpdate

Same as eslint rule https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-did-update-set-state.md

3. in componentWillMount

componentWillMount() is invoked immediately before mounting occurs. It is called before render(), therefore setting state in this method will not trigger a re-rendering. Avoid introducing any side-effects or subscriptions in this method.

jsx-wrap-multiline issue

Fails in both its with "tslint": "^4.1.1" and "tslint-react": "^2.2.0"

/* tslint:enable: jsx-wrap-multiline */
/**
 * React test
 */
import * as React from 'react';
import {
  TestComponent,
  ITestComponentProps
} from '../react-test-component';
import {
  mount,
  ReactWrapper
} from 'enzyme';

const renderer = require('react-test-renderer');

describe('react component', () => {
  let wrapper: ReactWrapper<ITestComponentProps, {}>;

  beforeEach(() => jest.resetModules());

  afterEach(() => {
    if (wrapper) {
      wrapper.unmount();
    }
  });

  it('Renders with enzyme', () => {
    wrapper = mount<ITestComponentProps, {}>(
      <TestComponent
        str1='My string'
      />
    );
    expect(wrapper.find(TestComponent).length)
      .toEqual(1);
  });

  it('Renders with jest test rendrer', () => {
    const component = renderer.create(
      <TestComponent
        str1='My string'
      />
    );
    const tree = component.toJSON();
    expect(tree).toMatchSnapshot();
  });
});

jsx-wrap-multiline is a breaking change

Hi,

Just wondered if you're using semantic versioning? We are extending tslint-react using version 2.*. The new jsx-wrap-multiline rule in 2.1 is causing our builds to fail without us making any changes to the default value which I believe should make it a breaking change. Am I wrong?

Thanks,
Luke

TS 2.3 API change breaks jsx-alignment

The above error seems to happen when using tslint 5.1.0, typescript 2.3.0; not sure how to reduce the input to a code snippet.

The unique part of the stack trace, for which I had to edit tslint/lib/linter.js to be able to obtain at all, looks like this:

TypeError: Cannot read property 'getStart' of undefined
  at JsxAlignmentWalker.getLineAndCharacter (.../node_modules/tslint-react/rules/jsxAlignmentRule.js:128:61)
  at JsxAlignmentWalker._this.getCharacter (.../node_modules/tslint-react/rules/jsxAlignmentRule.js:52:61)
  at JsxAlignmentWalker.checkElement (.../node_modules/tslint-react/rules/jsxAlignmentRule.js:80:39)
  at JsxAlignmentWalker.visitJsxElement (.../node_modules/tslint-react/rules/jsxAlignmentRule.js:60:18)
  at JsxAlignmentWalker.SyntaxWalker.visitNode (.../node_modules/tslint/lib/language/walker/syntaxWalker.js:401:22)
  at .../node_modules/tslint/lib/language/walker/syntaxWalker.js:530:63
  at visitEachNode (.../node_modules/typescript/lib/typescript.js:14674:30)
  at Object.forEachChild (.../node_modules/typescript/lib/typescript.js:14998:21)
  at JsxAlignmentWalker.SyntaxWalker.walkChildren (.../node_modules/tslint/lib/language/walker/syntaxWalker.js:530:12)
  at JsxAlignmentWalker.SyntaxWalker.visitJsxElement (.../node_modules/tslint/lib/language/walker/syntaxWalker.js:153:14)
  at JsxAlignmentWalker.visitJsxElement (.../node_modules/tslint-react/rules/jsxAlignmentRule.js:62:42)
  at JsxAlignmentWalker.SyntaxWalker.visitNode (.../node_modules/tslint/lib/language/walker/syntaxWalker.js:401:22)

New rule: no-unbound-method-callbacks

This is a mistake:

class MyComponent extends React.Component<{}, {}> {
  render() {
    return <button onClick={this.handleClick}>Click me!</button>;
    //                      ~~~~~~~~~~~~~~~~  passing unbound method
  }

  handleClick(e: any) {
    alert('You clicked!');
  }
}

There are many possible solutions, a few of which include:

  • onClick={this.handleClick.bind(this)}
  • onClick={e => this.handleClick(e)}
  • Adding this.handleClick = this.handleClick.bind(this); in the constructor

A lint rule would need to at least check for the last one to avoid false positives.

No lambda in JSX and lamda ref conflict

If ref defined as lamda, tslint warn about no lambda in JSX. But ref is string attr, tslint warn about callback to ref prop.

[tslint] Lambdas are forbidden in JSX attributes due to their rendering performance impact

<input type="input" ref={(c) => this._input = c} />

[tslint] Pass a callback to ref prop instead of a string literal

<input type="input" ref="input" />

jsx-alignment is slightly incompatible with VS Code auto-format

VS Code's auto-format yields

          <AutosizeInput
            onChange={onNameChange}
            placeholder="Name your project"
            placeholderIsMinWidth={true}
            value={props.name}
            />

But jsx-alignment wants

          <AutosizeInput
            onChange={onNameChange}
            placeholder="Name your project"
            placeholderIsMinWidth={true}
            value={props.name}
          />

Note that the last line is off by $indent spaces.

Is there a way to configure either VS Code or TSLint to make the two match up? I don't have a preference about which of the two conventions gets used.

Thanks for your time!

New Rule: Do not allow generation of new objects in props

Similar to jsx-no-lambda, if in a prop you do:

<MyComponent 
  style={{display: 'block'}}
/>

this will force any pure component to re-render every time.

Ideally, we could check in render to see if any new objects are generated there. Such as:

render() {
  const style = {display: 'block'};

  return <MyComponent 
    style={style}
  />
}

but that could be a separate rule.

jsx-curly-spacing has lint issues

There are four const related lint issues in jsx-curly-spacing:

src/rules/jsxCurlySpacingRule.ts[130, 21]: Identifier 'failureString' is never reassigned; use 'const' instead of 'let'.
src/rules/jsxCurlySpacingRule.ts[140, 21]: Identifier 'failureString' is never reassigned; use 'const' instead of 'let'.
src/rules/jsxCurlySpacingRule.ts[151, 25]: Identifier 'failureString' is never reassigned; use 'const' instead of 'let'.
src/rules/jsxCurlySpacingRule.ts[160, 25]: Identifier 'failureString' is never reassigned; use 'const' instead of 'let'.

jsx-use-translation-function option to specify which prop/attribute to check

the jsx-use-translation-function is very useful already, but it cannot identify problems when strings that need to be translated are passed in as certain props.
For example, if a component accepts a prop "label", we might want to be sure that is not a string literal.

The rule contains some hardcoded names (e.g. "title") that do get checked, but there's no way to specify extra ones in case a component uses one that is not part of that hardcoded list.

It would be very useful if the rule would accept an option to specify a list of prop/attribute names to check.

New Rule: component-method-names

(Seeking better rule name suggestions)

I want to enforce a certain naming pattern for callbacks and event handlers:

  • methods in props interfaces should use the on prefix -- this refers to code that binds handlers
  • methods on component classes should use the handle prefix -- these are the actual handlers that are bound by other methods

Development > Quick steps might use global TSLint during rules verification

scripts/verify.sh uses tslint executable from PATH and if launched not from npm/yarn script (as shown in Quick steps) will use global TSLint installation.

Possible solutions:

  1. Use tslint executable from node_modules in verify.sh file
    ./node_modules/.bin/tslint -r ./build/rules/ --test $path/..

  2. Add local installation to path in Quick steps
    PATH=./node_modules/.bin:$PATH ./scripts/verify.sh

add empty "index.js" to "rules/" directory

Given palantir/tslint#2163 it would be nice, if the rules/ directory would contain an empty index.js. Then we could resolve the rules directory with Nodes module resolution which makes it easy to use custom rules in certain situations (symlinked configs, flat vs. non-flat installations...).

Motivation:

  • extends: Allows me to use custom rules from other packages. I get all rules with default configs and can opt-out from rules. If new rules are added in new version I get them automatically.
  • rulesDirectory : Allows me to use custom rules from other packages. I opt-in to use certain rules with my specific configs. If new rules are added in new version I don't get them automatically.

Incompatible with tslint 4.0.1?

I upgraded tslint from 3.15.1 to 4.0.1 this morning and hit this error:

> [email protected] lint:tslint /Users/dfox/my-project
> tslint -c tslint.json 'src/**/*.ts*'

module.js:457
    throw err;
    ^

Error: Cannot find module 'tslint/lib/lint'
    at Function.Module._resolveFilename (module.js:455:15)
    at Function.Module._load (module.js:403:25)
    at Module.require (module.js:483:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/Users/dfox/my-project/node_modules/tslint-react/rules/jsxAlignmentRule.js:23:12)
    at Module._compile (module.js:556:32)
    at Object.Module._extensions..js (module.js:565:10)
    at Module.load (module.js:473:32)
    at tryModuleLoad (module.js:432:12)
    at Function.Module._load (module.js:424:3)

I've got tslint-react version 1.1.0 and a tslint.json containing:

{
  "extends": [
    "tslint:latest",
    "tslint-react"
  ],
  "rules": {
    "jsx-no-multiline-js": false,
    "jsx-no-string-ref": true,
    "jsx-self-close": true,
    "object-literal-sort-keys": false,
    "ordered-imports": false,
    "switch-default": false,
    "trailing-comma": [
      true,
      {
        "multiline": "never",
        "singleline": "never"
      }
    ]
  }
}

My guess is that the line import * as Lint from "tslint/lib/lint"; could actually be replaced by:

import * as Linter from "tslint";

Allow exceptions to "jsx-no-lambda" rule

I think the usage of lambdas in ref attributes can warrant an exception from the "jsx-no-lambda" rules, since this is an easy way to get type-safe access to rendered elements.

The only alternative I see would be to create instance functions which would be cumbersome to write and still have to be bound using .bind(this).

So until we have a nicer way to generate these "bindings" for example using macros, it would be nice to allow lambdas on some attributes.

More lenient jsx-no-multiline-js rule

I think the rule should be lenient about these kinds of multiline expressions because they don't hinder readability too much:

image

update: we should also add more exemptions:

  • allow-function-call to ignore function call expressions
  • allow-literal to ignore checking object and array literals
  • allow-element to ignore JSX elements

JSX Alignment Error Issue

Bug Report

  • TSLint version: 5.2.0
  • TypeScript version: 2.2.2
  • Running TSLint via: VSCode

TypeScript code being linted

render() {
        const suggestionsBottomOffset = 32 + (this.props.rows * 24) + 'px';

        return (
	    <div
                style={{
                    height: suggestionsBottomOffset
                }}
                className='textarea--wrapper'
            >
                {/* other code here but makes no difference to the error */}
	    </div>
	);
}

with tslint.json configuration:

{
    "defaultSeverity": "error",
    "extends": [
        "tslint:recommended",
        "tslint-react"
    ],
    "jsRules": {},
    "rules": {
        "indent": [false],
        "quotemark": [true, "single"],
        "object-literal-sort-keys": false,
        "ordered-imports": [
            false
        ],
        "interface-name": [
            false
        ],
        "member-access": [
            false
        ],
        "trailing-comma": [
            true,
            {
                "multiline": "never",
                "singleline": "never"
            }
        ],
        "arrow-parens": false,
        "jsx-wrap-multiline": false,
        "jsx-no-lambda": false,
        "jsx-no-multiline-js": false,
        "eofline": false,
        "jsx-self-close": false,
        "jsx-boolean-value": false,
        "no-unused-expression": false
    },
    "rulesDirectory": []
}

Actual behavior

This produces an error on the rule "jsx-alignment" - "Tag closing must be on its own line and aligned with the opening of tag."
screen shot 2017-05-11 at 11 42 45

This error seems to occur only when the element in question is the outermost element, i.e. it does not appear in this situation:
screen shot 2017-05-11 at 11 47 35

Expected behavior

No error.

"Could not find implementations (...) jsx-wrap-multiline"

Running tslint with the following minimal configuration fails with [email protected] (but works with 2.0.0):

{
  "extends": [
    "tslint-react"
  ]
}

The error message is the following, printed for each of the linted files:

Could not find implementations for the following rules specified in the configuration:
    jsx-wrap-multiline
Try upgrading TSLint and/or ensuring that you have all necessary custom rules installed.
If TSLint was recently upgraded, you may have old rules configured which need to be cleaned up.

no-unused-variable

no-unused-variable warning highlighting defaultProps and componentDidMount. I think it is wrong, is not it?

export default class App extends React.Component<any, ICounterState> {
  private static defaultProps = {
    title: "wefwef",
  };
  private unsubscribe: any;
  constructor(props: any) {
    super(props);
    this.state = store.getState();
  }
  public render() {
    return (
      <div>
        <button onClick={this.handlePlusClick}>+</button>
        <button onClick={this.handleMinusClick}>-</button>
        <div>{this.state.counter}</div>
      </div>
    );
  }
  private componentDidMount() {
    this.unsubscribe = store.subscribe(this.handleStoreUpdate);
  }
  private handleStoreUpdate = () => {
    this.setState(store.getState());
  }
  private handlePlusClick = () => {
    store.dispatch(increment());
  }
  private handleMinusClick = () => {
    store.dispatch(increment());
  }
}

New rule: react-no-throw-in-lifecycle

some good advice from @crazytoucan (abridged):

Sometimes your whole app crashes, because of a single React component that threw: maybe render() tried to map an array that was undefined, or WillMount() tried to talk to a service that threw internally
...
there’s ultimately no reliable way to recover from a crashed component as a library or utility.
...
Simply put, you should never throw inside your React lifecycle methods. If this means a little bit of extra defensive programming, I think component resilience is a worthwhile cost. Don’t litter code with unnecessary invariant checks ...

We should look into a lint rule that can enforce this.

jsxWrapMultilineRule: TypeError: Cannot read property 'some' of undefined

[email protected]

Happens with phpStorm tslint integration

TypeError: Cannot read property 'some' of undefined
    at Object.doesIntersect (/devel/src/hotfix/megaplan/front/node_modules/tslint/lib/language/utils.js:27:29)
    at _loop_1 (/devel/src/hotfix/megaplan/front/node_modules/tslint/lib/language/rule/abstractRule.js:47:26)
    at Rule.AbstractRule.filterFailures (/devel/src/hotfix/megaplan/front/node_modules/tslint/lib/language/rule/abstractRule.js:54:13)
    at Rule.AbstractRule.applyWithWalker (/devel/src/hotfix/megaplan/front/node_modules/tslint/lib/language/rule/abstractRule.js:33:21)
    at Rule.apply (/devel/src/hotfix/megaplan/front/node_modules/tslint-react/rules/jsxWrapMultilineRule.js:31:21)
    at Linter.applyRule (/usr/lib/node_modules/tslint/lib/linter.js:138:33)
    at Linter.lint (/usr/lib/node_modules/tslint/lib/linter.js:104:41)
    at TSLintPlugin.processLinting (/devel/bin/PhpStorm-171.3780.55/plugins/tslint/tslintLanguageService/tslint-plugin.js:76:20)
    at TSLintPlugin.getErrors (/devel/bin/PhpStorm-171.3780.55/plugins/tslint/tslintLanguageService/tslint-plugin.js:54:21)
    at TSLintPlugin.process (/devel/bin/PhpStorm-171.3780.55/plugins/tslint/tslintLanguageService/tslint-plugin.js:22:29)

Allow for ignoring closing "/>" position when jsx-alignment is enabled

Would you consider merging in a PR which adds a rule option for ignoring the position of the closing "/>" ?

I'm asking because I would like to get the main benefit of this rule (only one JSX element per line) without having to worry about where the closing "/>" is located. I will implement this if it's something you would be OK with merging.

Improve "jsx-no-lambda" rule detection

This rule is reporting false positives in situations where the lambda is used as a parameter to a function returning some value. For example:

interface Item { value: number; }

<Currency amount={ _.sumBy(items, (item: Item) => item.value) } />

This usage does not have any negative implications with regards to the shallowCompare render optimisation as the lambda is never actually compared.

I am aware that simple workaround would often be to compute the value into a variable and then use it like this:

interface Item { value: number; }

const total = _.sumBy(items, (item: Item) => item.value);
<Currency amount={ total } />

However, that seems tedious and unnecessary.

New rule: react-variable-name

Some variable name identifiers are potentially confusing inside component methods.

I'd like to ban:

  • state (either const state or const { state } = foo). This is too similar to this.state.
  • more to come...

New rule: react-context-args

https://facebook.github.io/react/docs/context.html#referencing-context-in-lifecycle-methods

If contextTypes is defined on a component, the following methods should be defined with the additional context trailing argument. If not defined, the arguments should be omitted.

  • constructor(props, context)
  • componentWillReceiveProps(nextProps, nextContext)
  • shouldComponentUpdate(nextProps, nextState, nextContext)
  • componentWillUpdate(nextProps, nextState, nextContext)
  • componentDidUpdate(prevProps, prevState, prevContext)

New Rule: component-constructor-signature

Require all constructors to include both props and context as parameters, not just props (a common mistake that breaks libraries that rely on context.

constructor(props: SomeType, context?: any) {
    super(props, context);
}

New Rule: component-display-name

Require public static displayName property on classes that extend React.Component.

Since we don't have the type checker yet, this will only be able to verify classes that directly extend React.Component, not any subclasses of it.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.