Giter Site home page Giter Site logo

eslint-plugin-react-native's Introduction

.__        __         .__  .__  .__                 .___      
|__| _____/  |_  ____ |  | |  | |__| ____  ____   __| _/____  
|  |/    \   __\/ __ \|  | |  | |  |/ ___\/  _ \ / __ |/ __ \ 
|  |   |  \  | \  ___/|  |_|  |_|  \  \__(  <_> ) /_/ \  ___/ 
|__|___|  /__|  \___  >____/____/__|\___  >____/\____ |\___  >
        \/          \/                  \/           \/    \/ 

eslint-plugin-react-native's People

Contributors

aleksandrzhukov avatar bspaulding avatar cooperka avatar dependabot[bot] avatar doochik avatar draperunner avatar greenkeeper[bot] avatar greenkeeperio-bot avatar intellicode avatar jrzimmerman avatar kfiroo avatar markrickert avatar marneborn avatar mattyclarkson avatar maxaggedon avatar nclshart avatar nisalvd avatar note89 avatar radko93 avatar rdy avatar rickdunkin avatar satya164 avatar shirohana avatar snowcoderalex avatar sstur avatar stevepotter avatar tanhauhau avatar tigershen23 avatar wakeless avatar xxsnakerxx 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

eslint-plugin-react-native's Issues

no-unused-styles doesn't work with functions and vars

when I added the rule for no-unused-styles to my project I got many errors.
most of them were due to styles dynamically loaded from functions or vars.

consider the following use cases:

class MyView extends Component {

  static propTypes = {
    isActive: React.PropTypes.bool,
    type: React.PropTypes.oneOf(['typeA', 'typeB'])
  };

  get myActiveStyle() {
     return this.props.isActive ? style.active : {}
  }

 render() {
    var typeStyle = styles[this.props.type];
    return (
      <View style={[this.activeStyle, typeStyle]} / >
    );
  }

}

// All 3 styles will be marked as unused
const styles = StyleSheet.create({
   active: {...},
   typeA: {...},
   typeB: {...},
})

my current solution is to wrap the erroring code with:

/*eslint-disable react-native/no-unused-styles */
 const styles = StyleSheet.create({...});
/*eslint-enable react-native/no-unused-styles */

Thoughts?

Enforce naming conventions

To improve consistency within an app it is often desirable to name components in a structured way, for example:

  • List
  • Page
  • Scene
  • <...>Notification

If there is any interest, please let me know by writing a comment

Split platform components rule not parsing imports

The split-platform-components rule only parses the components on destructuring assignments taken from the React variable.

One common practice is to import the components directly from react-native:

import React from 'react'
import { ActivityIndicatiorIOS } from 'react-native' // Import pattern not detected

export default function Hello() {
  return <ActivityIndicatiorIOS/>
}

Please consider adding that pattern to the rule.

update 1.0.1 broke eslint config with `"react-native/no-unused-styles": "error",`

with 1.0.0 everything worked,
now I get:

Cannot read property 'type' of undefined
TypeError: Cannot read property 'type' of undefined
    at Object.StyleSheets.markAsUsed.astHelpers.collectStyleReferencesFromContainers.getStyleReferenceFromNode (/Users/danielzl/dev/wix-one-app/node_modules/eslint-plugin-react-native/lib/util/stylesheet.js:138:17)
    at Object.StyleSheets.markAsUsed.astHelpers.collectStyleReferences (/Users/danielzl/dev/wix-one-app/node_modules/eslint-plugin-react-native/lib/util/stylesheet.js:121:23)
    at EventEmitter.unusedStyles.JSXAttribute.node (/Users/danielzl/dev/wix-one-app/node_modules/eslint-plugin-react-native/lib/rules/no-unused-styles.js:45:35)
    at emitOne (events.js:95:20)
    at EventEmitter.emit (events.js:182:7)
    at NodeEventGenerator.enterNode (/Users/danielzl/dev/wix-one-app/node_modules/eslint/lib/util/node-event-generator.js:40:22)
    at CodePathAnalyzer.enterNode (/Users/danielzl/dev/wix-one-app/node_modules/eslint/lib/code-path-analysis/code-path-analyzer.js:607:23)
    at CommentEventGenerator.enterNode (/Users/danielzl/dev/wix-one-app/node_modules/eslint/lib/util/comment-event-generator.js:97:23)
    at Controller.traverser.traverse.enter (/Users/danielzl/dev/wix-one-app/node_modules/eslint/lib/eslint.js:886:36)
    at Controller.__execute (/Users/danielzl/dev/wix-one-app/node_modules/eslint/node_modules/estraverse/estraverse.js:397:31)

removing the line "react-native/no-unused-styles": "error", OR reverting to 1.0.0 fixes the issue.

new rules idea: no-inline-styles, no-color-literals

Thanks for this plugin, these are useful rules.

I think it would be nice to be able to detect inline styles in components and either warn/error when detected. We prefer style objects over littering the components with object literals with styles in them.

(There are cases where inline styles are appropriate, like when they use props/state and aren't available outside the render method. These would be exceptions to the rule.)

I've been working on this rule a bit, if it's something you'd accept I'd be happy to send a PR. Thanks!

TypeError: Cannot read property 'type' of null

my error when i type style attribute:

TypeError: Cannot read property 'type' of null
    at Object.astHelpers.hasArrayOfStyleReferences (/home/afdalwahyu/Documents/projects/gagclone/node_modules/eslint-plugin-react-native/lib/util/stylesheet.js:312:11)
    at Object.astHelpers.collectStyleReferences (/home/afdalwahyu/Documents/projects/gagclone/node_modules/eslint-plugin-react-native/lib/util/stylesheet.js:157:20)
    at EventEmitter.JSXAttribute (/home/afdalwahyu/Documents/projects/gagclone/node_modules/eslint-plugin-react-native/lib/rules/no-unused-styles.js:46:35)
    at emitOne (events.js:95:20)
    at EventEmitter.emit (events.js:182:7)
    at NodeEventGenerator.enterNode (/home/afdalwahyu/Documents/projects/gagclone/node_modules/eslint/lib/util/node-event-generator.js:40:22)
    at CodePathAnalyzer.enterNode (/home/afdalwahyu/Documents/projects/gagclone/node_modules/eslint/lib/code-path-analysis/code-path-analyzer.js:608:23)
    at CommentEventGenerator.enterNode (/home/afdalwahyu/Documents/projects/gagclone/node_modules/eslint/lib/util/comment-event-generator.js:97:23)
    at Controller.enter (/home/afdalwahyu/Documents/projects/gagclone/node_modules/eslint/lib/eslint.js:927:36)
    at Controller.__execute (/home/afdalwahyu/Documents/projects/gagclone/node_modules/estraverse/estraverse.js:397:31)

.eslintrc rules that make eslint show error

  "rules": {
    ....
    "react-native/no-unused-styles": 2,
    .....
  }

I'm using

[email protected]

Error: Definition for rule 'react-native/no-inline-styles' was not found

My .eslintrc file:

{
"parserOptions": {
"ecmaVersion": 7,
"sourceType": "module",
"ecmaFeatures": {
"jsx": true,
}
},
"env": {
"browser": true,
"node": true
},
"plugins": [
"react",
"react-native"
],
"extends": ["eslint:recommended", "plugin:react/recommended"],
"rules": {
"react-native/no-unused-styles": 2,
"react-native/split-platform-components": 2,
"react-native/no-inline-styles": 2,
"react-native/no-color-literals": 2,
"no-console":0,
"no-alert":0
},
"settings": {
"react": {
"pragma": "React",
"version": "15.1.0"
}
},
"globals": { "fetch": false }
}

Show warning when using an undefined style

const styles = StyleSheet.create({});

const Hello = React.createClass({
  render: function() {
    return <Text style={styles.name}>Hello {this.props.name}</Text>;
  }
});

Should throw a warning regarding styles.name

Headers still get error "no-undef"

my code like:
option: {
method: 'POST',
headers: new Headers({
'X-Api-Key': 'xxxxxxxxxxxxxxxx',
'Content-Type': 'application/json'
})
}

then eslint tell me "no-undef" at Headers

Globals no longer includes navigator.geolocation

Hope the title makes sense. Not the most familiar with ESLInt rules etc. I've had to do the following to suppress for the moment:

// eslint-disable-next-line no-undef
    navigator.geolocation.getCurrentPosition(

Composing stylesheets counts as failure

By using the following syntax const style = {...commonStyle, ...specificStyle}. I can combine two stylesheets into one.

However, even though the styles are used through the style object, the styles from the specificStyle sheet count as unused.

Detect computed properties in constructor

  // Component WelcomeBar
  import React, { Component } from 'react';
  import { Text, View, Image } from 'react-native';
  import styles from './styles';

  export default class WelcomeBar extends Component {
    constructor(props) {
      super(props);
      // Code Smell
      this.state = {fullName: this.props.firstName + this.props.lastName}
    }
    render() {
      // This will not change on subsequent renders
      return (<Text>{this.state.fullName}</Text>);
    }
  }


  // Component WelcomePage
  import React, { Component } from 'react';
  import { Text, View, Image } from 'react-native';
  import styles from './styles';
  export default class WelcomePage extends Component {
    someMethod() {
      this.setState({lastName: 'Modified'});
    }

    render() {
      return (
        <View>
          <WelcomeBar isUserLoggedIn={true} firstName=this.state.firstName lastName=this.state.lastName />
          <WelcomeMessage />
        </View>
      );
    }
  }

In the above example, WelcomeBar is re-rendered by WelcomePage when someMethod is executed. However it doesn't update the fullName.
This could have been avoided by listening to the deprecated componentWillReceiveProps or the getDerivedStateFromProps. However, this kind of code is smell to be in the first place. Can this be detected in es-lint please?

Environment key "react-native/react-native" is unknown

"eslint": "^4.11.0",
"eslint-plugin-react": "^7.4.0",
"eslint-plugin-react-native": "^3.1.0",

And, this is my .eslintrc.json

{
    "parser": "babel-eslint",
    "env": {
        "browser": true,
        "node": true,
        "commonjs": true,
        "es6": true,
        "react-native/react-native": true
    },
    "extends": ["eslint:recommended", "plugin:react/recommended"],
    "parserOptions": {
        "ecmaFeatures": {
            "experimentalObjectRestSpread": true,
            "jsx": true
        },
        "sourceType": "module"
    },
    "plugins": ["react", "react-native"],
    "rules": {
        "indent": ["error", 4, { "SwitchCase": 1 }],
        "quotes": ["error", "single"],
        "semi": ["error", "always", { "omitLastInOneLineBlock": true }],
        "no-unused-vars": [1],
        "no-console": [1],
        "react/prop-types": 1,
        "react/display-name":1
    }
}

[Feature request] Rule no-undefined-styles

After a refactoring, I left my code with undefined entries in the StyleSheet. No errors at runtime but it has lead to cosmetic bugs, hard to catch.

It would have been great if eslint had warned me.

Example of invalid code: (styles.startButton and styles.disabled aren't defined)

const styles = StyleSheet.create({
  startView: {
    justifyContent: 'center',
  },
});

render() {
  return (
    <View style={styles.startView}>
      <Button style={[styles.startButton, this.props.disabled && styles.disabled]} />
    </View>
  );
}

This rule would be kind of the opposite of no-unused-styles.

An in-range update of eslint is breaking the build ๐Ÿšจ

Version 4.4.0 of eslint just got published.

Branch Build failing ๐Ÿšจ
Dependency eslint
Current Version 4.3.0
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

As eslint is โ€œonlyโ€ a devDependency of this project it might not break production or downstream projects, but โ€œonlyโ€ your build or test tools โ€“ preventing new deploys or publishes.

I recommend you give this issue a high priority. Iโ€™m sure you can resolve this ๐Ÿ’ช

Status Details
  • โŒ continuous-integration/travis-ci/push The Travis CI build failed Details

Release Notes v4.4.0
  • 89196fd Upgrade: Espree to 3.5.0 (#9074) (Gyandeep Singh)
  • b3e4598 Fix: clarify AST and don't use node.start/node.end (fixes #8956) (#8984) (Toru Nagashima)
  • 62911e4 Update: Add ImportDeclaration option to indent rule (#8955) (David Irvine)
  • de75f9b Chore: enable object-curly-newline & object-property-newline.(fixes #9042) (#9068) (่–›ๅฎš่ฐ”็š„็Œซ)
  • 5ae8458 Docs: fix typo in object-shorthand.md (#9066) (Jon Berry)
  • c3d5b39 Docs: clarify options descriptions (fixes #8875) (#9060) (Brandon Mailhiot)
  • 37158c5 Docs: clarified behavior of globalReturn option (fixes #8953) (#9058) (Brandon Mailhiot)
  • c2f3553 Docs: Update example for MemberExpression option of indent (fixes #9056) (#9057) (Jeff)
  • 78a85e0 Fix: no-extra-parens incorrectly reports async function expressions (#9035) (่–›ๅฎš่ฐ”็š„็Œซ)
  • c794f86 Fix: getter-return reporting method named 'get' (fixes #8919) (#9004) (่–›ๅฎš่ฐ”็š„็Œซ)
  • d0f78ec Docs: update rule deprecation policy (fixes #8635) (#9033) (Teddy Katz)
  • 5ab282f Fix: Print error message in bin/eslint.js (fixes #9011) (#9041) (Victor Hom)
  • 50e3cf3 Docs: Update sort-keys doc to define natural ordering (fixes #9043) (#9045) (Karan Sharma)
  • 7ecfe6a Chore: enable eslint-plugin/test-case-property-ordering (#9040) (่–›ๅฎš่ฐ”็š„็Œซ)
  • ad32697 Upgrade: js-yaml to 3.9.1 (refs #9011) (#9044) (Teddy Katz)
  • 66c1d43 Docs: Create SUPPORT.md (#9031) (Teddy Katz)
  • 7247b6c Update: handle indentation of custom destructuring syntax (fixes #8990) (#9027) (Teddy Katz)
  • cdb82f2 Fix: padding-line-between-statements crash on semicolons after blocks (#8748) (Alexander Madyankin)
  • 3141872 Chore: remove unnecessary eslint-disable comments in codebase (#9032) (Teddy Katz)
  • 0f97279 Fix: refactor no-multi-spaces to avoid regex backtracking (fixes #9001) (#9008) (Teddy Katz)
  • b74514d Fix: refactor RuleContext to not modify report locations (fixes #8980) (#8997) (Teddy Katz)
  • 31d7fd2 Fix: inconsistent indent behavior on computed properties (fixes #8989) (#8999) (Teddy Katz)
  • 3393894 Fix: avoid reporting the entire AST for missing rules (#8998) (Teddy Katz)
  • b3b95b8 Chore: enable additional rules on ESLint codebase (#9013) (Teddy Katz)
  • 9b6c552 Upgrade: [email protected] (#9012) (่–›ๅฎš่ฐ”็š„็Œซ)
  • acbe86a Chore: disallow .substr and .substring in favor of .slice (#9010) (Teddy Katz)
  • d0536d6 Chore: Optimizes adding Linter methods (fixes #9000) (#9007) (Sean C Denison)
  • 0a0401f Chore: fix spelling error. (#9003) (่–›ๅฎš่ฐ”็š„็Œซ)
  • 3d020b9 Update: emit a warning for ecmaFeatures rather than throwing an error (#8974) (Teddy Katz)
  • d2f8f9f Fix: include name of invalid config in validation messages (fixes #8963) (#8973) (Teddy Katz)
  • c3ee46b Chore: fix misleading comment in RuleTester (#8995) (Teddy Katz)
Commits

The new version differs by 33 commits.

  • a113cd3 4.4.0
  • 181bd46 Build: changelog update for 4.4.0
  • 89196fd Upgrade: Espree to 3.5.0 (#9074)
  • b3e4598 Fix: clarify AST and don't use node.start/node.end (fixes #8956) (#8984)
  • 62911e4 Update: Add ImportDeclaration option to indent rule (#8955)
  • de75f9b Chore: enable object-curly-newline & object-property-newline.(fixes #9042) (#9068)
  • 5ae8458 Docs: fix typo in object-shorthand.md (#9066)
  • c3d5b39 Docs: clarify options descriptions (fixes #8875) (#9060)
  • 37158c5 Docs: clarified behavior of globalReturn option (fixes #8953) (#9058)
  • c2f3553 Docs: Update example for MemberExpression option of indent (fixes #9056) (#9057)
  • 78a85e0 Fix: no-extra-parens incorrectly reports async function expressions (#9035)
  • c794f86 Fix: getter-return reporting method named 'get' (fixes #8919) (#9004)
  • d0f78ec Docs: update rule deprecation policy (fixes #8635) (#9033)
  • 5ab282f Fix: Print error message in bin/eslint.js (fixes #9011) (#9041)
  • 50e3cf3 Docs: Update sort-keys doc to define natural ordering (fixes #9043) (#9045)

There are 33 commits in total.

See the full diff

Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot ๐ŸŒด

no-empty-styles

Had an idea for a rule to throw in this case:

const React = require('react');
const { StyleSheet, View } = require('react-native');

const styles = StyleSheet.create({
	list: {}
});

function SomeComponent(){
	return <View style={styles.list} />;
}

module.exports = SomeComponent;

no-use-before-define

Would it be possible to have some rule that StyleSheet.create-variables can be used before defined? If I understand correctly that is the best practice and that collides with no-use-before-define

no-unused-styles doesn't support conditional styles

I often add conditional styles to my components and no-unused-styles doesn't see that the style is actually used in the code.

const styles = StyleSheet.create({
  container: {
    padding: 1,
  },
  'container--critical': {
    backgroundColor: MY_RED_CONST,
  },
});

const Component = ({ shouldBeRed }) => (
  <View style={[styles.container].concat(shouldBeRed ? styles['container--critical'] : [])}>
    <Text>This is some text</Text>
  </View>
);

no-inline-styles fails with unary minus

Assume component:

class Foo extends Component {
  render() {
    return (
      <View>
        <Text style={{margin: -this.props.margin}}>Bar</Text>
      </View>
    )
  }
}

Then no-inline-styles reports:

10:22  error  Inline style: { margin: NaN }              react-native/no-inline-styles

It fails to recognize that -this.props.margin is an expression. It does not report for this.props.margin (without the minus sign) nor for -1 * this.props.margin.

eslint-plugin-react-native version: 3.2.1
eslint version: 4.16.0

Rule to detect JSX text not in a Text component

In some components such as View, text can not be placed directly inside (it must be wrapped with a Text component).

Could you add a rule for this ? Ideally list of standard component forbidding direct use of text could be completed with a rule configuration.

ecmaFeatures error

I am getting

	ESLint configuration is invalid:
	- Unexpected top-level property "ecmaFeatures".

when using this as my .eslinrc file

{
  "plugins": [
    "react",
    "react-native"
  ],
  "env": {
    "es6": true,
    "node": true
  },
  "parserOptions": {
    "ecmaVersion": 6,
    "ecmaFeatures": {
      "jsx": true
    }
  },
  "rules": {
    "no-const-assign": "warn",
    "no-this-before-super": "warn",
    "no-undef": "warn",
    "no-unreachable": "warn",
    "no-unused-vars": "warn",
    "constructor-super": "warn",
    "valid-typeof": "warn"
  }
}

no-unused-styles does not support destructuring assignment

The styles are are marked as errors when the styles are destructed. Destructuring Assignment

class App extends Component {
  render() {
    const { container, welcome, instructions } = styles;

    return (
      <View style={container}>
        <Text style={welcome}>
          Welcome to React Native!
        </Text>
        <Text style={instructions}>
          To get started, edit index.ios.js
        </Text>
        <Text style={instructions}>
          Press Cmd+R to reload,{'\n'}
          Cmd+D or shake for dev menu
        </Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

TypeError in no-inline-styles rule

This is similar to #60, but now occurs in the no-inline-styles rule instead of the no-unused-styles rule. It looks like #60 was fixed in 2.2.0, but that has now exposed this new issue.

When I'm working in Atom with the linter-eslint plugin, I often encounter a TypeError that originates in the no-inline-styles rule while I'm typing. I have linter-eslint configured to lint as I type.

I have found that the code that triggers the error contains the fragment <View style>. So, I'm in the process of adding style information, but before I can add the = {}, I get the type error.

I'm using eslint-plugin-react-native 2.2.0.

Here's the stack trace:

TypeError: Cannot read property 'expression' of null
    at Object.collectStyleObjectExpressions (/Users/randy/src/linx/SmartLinx/node_modules/eslint-plugin-react-native/lib/util/stylesheet.js:170:60)
    at EventEmitter.JSXAttribute (/Users/randy/src/linx/SmartLinx/node_modules/eslint-plugin-react-native/lib/rules/no-inline-styles.js:36:35)
    at emitOne (events.js:101:20)
    at EventEmitter.emit (events.js:188:7)
    at NodeEventGenerator.enterNode (/Users/randy/src/linx/SmartLinx/node_modules/eslint/lib/util/node-event-generator.js:40:22)
    at CodePathAnalyzer.enterNode (/Users/randy/src/linx/SmartLinx/node_modules/eslint/lib/code-path-analysis/code-path-analyzer.js:608:23)
    at CommentEventGenerator.enterNode (/Users/randy/src/linx/SmartLinx/node_modules/eslint/lib/util/comment-event-generator.js:97:23)
    at Controller.enter (/Users/randy/src/linx/SmartLinx/node_modules/eslint/lib/eslint.js:925:36)
    at Controller.__execute (/Users/randy/src/linx/SmartLinx/node_modules/estraverse/estraverse.js:397:31)
    at Controller.traverse (/Users/randy/src/linx/SmartLinx/node_modules/estraverse/estraverse.js:501:28)

UNMET PEER DEPENDENCY [email protected]

eslint-plugin-react-native 2.3.0 now requires eslint 3.12.1 to be installed on project (peerDependencies). But latest commits clear about real required version of eslint, it should be 3.17.0 (as in devDependencies).

Seems like greenkeeper.io bot ignores peerDependencies.

Conditional Style Marked as Inline

Currently I'm getting flagged for this.

<div
  style={{
    ...styles.mainContainer,
    left: (left === 0) ? 0 : container.left, // eslint-disable-line react-native/no-inline-styles
  }}
>

Is this really some anti-pattern?
Thanks for your time.

Wrong `no-unused-style` warning with conditional styles

Sample code to reproduce:

import React, { Component, PropTypes } from 'react';
import ReactNative from 'react-native';

const {
    StyleSheet,
    View
} = ReactNative;

const styles = StyleSheet.create({
    style1: {
        color: 'red',
    },
    style2: {
        color: 'blue',
    }
});

export default class MyComponent extends Component {
    static propTypes = {
        isDanger: PropTypes.bool
    };

    render() {
        return <View style={this.props.isDanger ? styles.style1 : styles.style2} />;
    }
}

ESLint output:

/path/to/test.js
  10:2  warning  Unused style detected: styles.style1  react-native/no-unused-styles
  13:2  warning  Unused style detected: styles.style2  react-native/no-unused-styles

โœ– 2 problems (0 errors, 2 warnings)

ESLint config:

    "react-native/no-unused-styles": 1,
    "react-native/split-platform-components": 1,

Detect not imported element

I often loose my mind looking for vicious a bug whereas I only forgot to import one of the native elements I am using... The no-undef classic rule is not triggering.

Is there a walk around ?

Thanks

magic numbers inside stylesheet

Hello, I was wondering how to properly setup this plugin in order I stop getting warnings like 9:15 warning No magic number: 20 no-magic-numbers within styles block such as:

const styles = StyleSheet.create({
  container: {
    flex: 1
    , justifyContent: 'center'
    , alignItems: 'center'
    , backgroundColor: '#F5FCFF'
  }
  , welcome: {
    fontSize: 20
    , textAlign: 'center'
    , margin: 10
  }
  , instructions: {
    textAlign: 'center'
    , color: '#333333'
    , marginBottom: 5
  }
})

This plugin offers any solution to this matter?

TypeError in no-unused-styles rule

When I'm working in Atom with the linter-eslint plugin, I often encounter a TypeError that originates in the no-used-styles rule while I'm typing. I have linter-eslint configured to lint as I type.

I have found that the code that triggers the error contains the fragment <View style>. So, I'm in the process of adding style information, but before I can add the = {}, I get the type error.

I'm using eslint-plugin-react-native 2.0.0.

Here's the stack trace:

TypeError: Cannot read property 'type' of null
    at Object.astHelpers.hasArrayOfStyleReferences (/path/to/myProject/node_modules/eslint-plugin-react-native/lib/util/stylesheet.js:312:11)
    at Object.astHelpers.collectStyleReferences (/path/to/myProject/node_modules/eslint-plugin-react-native/lib/util/stylesheet.js:157:20)
    at EventEmitter.JSXAttribute (/path/to/myProject/node_modules/eslint-plugin-react-native/lib/rules/no-unused-styles.js:46:35)
    at emitOne (events.js:95:20)
    at EventEmitter.emit (events.js:182:7)
    at NodeEventGenerator.enterNode (/path/to/myProject/node_modules/eslint/lib/util/node-event-generator.js:40:22)
    at CodePathAnalyzer.enterNode (/path/to/myProject/node_modules/eslint/lib/code-path-analysis/code-path-analyzer.js:608:23)
    at CommentEventGenerator.enterNode (/path/to/myProject/node_modules/eslint/lib/util/comment-event-generator.js:97:23)
    at Controller.enter (/path/to/myProject/node_modules/eslint/lib/eslint.js:895:36)
    at Controller.__execute (/path/to/myProject/node_modules/eslint/node_modules/estraverse/estraverse.js:397:31)

Support for browser-like globals

React Native ships with some polyfills that mimic the interface from browsers (ie: setInterval, clearInterval, Geolocation API, etc...). It would be cool to have these in react-native to avoid using env: browser: true.

Spread operator in StyleSheet causes linter to crash

When I define a StyleSheet with a spread operator, the linter crashes.

Version

"eslint-plugin-react-native": "^2.2.1",

StyleSheet
const styles = StyleSheet.create({
  ...SettingsStyles,
  image: {
    height: 90,
    width: 90,
    borderRadius: 45,
  },
  profile: {
    flex: 1,
  },
  avatar: {
    alignItems: 'center',
    justifyContent: 'center',
    paddingTop: 15,
    paddingBottom: 15,
  },
});
Error
Cannot read property 'name' of undefined
TypeError: Cannot read property 'name' of undefined
    at styleSheets.(anonymous function).styleSheets.(anonymous function).filter.property (/Users/upside/src/upside-rewards/upside-rewards-native/node_modules/eslint-plugin-react-native/lib/util/stylesheet.js:37:41)
    at Array.filter (native)
    at StyleSheets.markAsUsed (/Users/upside/src/upside-rewards/upside-rewards-native/node_modules/eslint-plugin-react-native/lib/util/stylesheet.js:37:10)
    at Program:exit.styleReferences.forEach (/Users/upside/src/upside-rewards/upside-rewards-native/node_modules/eslint-plugin-react-native/lib/rules/no-unused-styles.js:57:23)
    at Set.forEach (native)
    at EventEmitter.Program:exit (/Users/upside/src/upside-rewards/upside-rewards-native/node_modules/eslint-plugin-react-native/lib/rules/no-unused-styles.js:56:25)
    at emitOne (events.js:101:20)
    at EventEmitter.emit (events.js:188:7)
    at NodeEventGenerator.leaveNode (/Users/upside/src/upside-rewards/upside-rewards-native/node_modules/eslint/lib/util/node-event-generator.js:48:22)
    at CodePathAnalyzer.leaveNode (/Users/upside/src/upside-rewards/upside-rewards-native/node_modules/eslint/lib/code-path-analysis/code-path-analyzer.js:627:23)
    at CommentEventGenerator.leaveNode (/Users/upside/src/upside-rewards/upside-rewards-native/node_modules/eslint/lib/util/comment-event-generator.js:111:23)
    at Controller.leave (/Users/upside/src/upside-rewards/upside-rewards-native/node_modules/eslint/lib/eslint.js:931:36)
Workaround
const combineStyles = {
  ...SettingsStyles,
  image: {
    height: 90,
    width: 90,
    borderRadius: 45,
  },
  profile: {
    flex: 1,
  },
  avatar: {
    alignItems: 'center',
    justifyContent: 'center',
    paddingTop: 15,
    paddingBottom: 15,
  },
}

const styles = StyleSheet.create(combineStyles);
Related Tickets

Handle unrecognized eslint nodes in style rules helper #49
update 1.0.1 broke eslint config with "react-native/no-unused-styles": "error", #21

Conditional styles marked as unused

Here's a truncated example:

const styles = StyleSheet.create({
  checked: {
    borderColor: colors.green,
    backgroundColor: colors.green,
  },
});
<View style={[payment.status === 'Checked' && styles.checked]} />

Unused style detected: styles.checked

I would say if a style can be conditionally applied, it should be marked as 'used'. If you agree I can try for a PR.

split-platform-components and Platform module / Expo

Seeing as how many eslint question seem to be ignored on StackOverflow, I've decided to ask this here.

Should the split-plaform-components rule be ignored when developing an RN app with Expo? In a more general sense, is there a subset of rules that shouldn't apply to apps being developed with this toolset?

Perhaps a better question is: Should this rule not raise a warning when the file in question is using the Platform module?

Platform.select({
  ios: <IOSonlyComponent/>,
  android: <AndroidOnlyComponent/>
})

no-unused-styles shows error when style object property names are quoted

no-unused-styles reports unused style detected when the style object property names are quoted

const styles = StyleSheet.create({
    'container': {
        alignItems: 'center',
        backgroundColor: Color.white,
        flex: 1,
        justifyContent: 'center'
    }
});

/** Returns the application's root component
 * @returns {React.Component} root component
 */
export default function App () {

    return (
        <View style={styles.container}>
            <Text>Open up App.js to start working on your app!</Text>
            <Text>Changes you make will automatically reload.</Text>
            <Text>Shake your phone to open the developer menu.</Text>
        </View>
    );

}
eslint App.js
6:5  error  Unused style detected: styles                    react-native/no-unused-styles

Extends a recommended set of rules for native ?

Hi,

I was checking over at the react plugin (non native) and I notice they offer some extending which sets up a recommended config.

"extends": ["eslint:recommended", "plugin:react/recommended"]

I was wondering if something exists in this plugin also ?

Thanks

Enforce platform specific components

When platform specific components are used, check that the filename includes the specific platform. For example when LinkingIOS is used, the component should be named xxx.ios.js

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.