Lint rules related to React & JSX for TSLint.

Last update: May 4, 2022

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.
    {children}
    ; // Also Good: ">
    // 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
    // good
    ">
    // 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.
    Submit ; // good const button = ( ); ">
    // 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.

GitHub

https://github.com/palantir/tslint-react
Comments
  • 1. 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>
    );
    
    Reviewed by paranoidjk at 2017-03-28 15:23
  • 2. Can't use Pascal case when declaring a stateless functional component (SFC)

    I'm currently having issues declaring SFCs when using the following tslint configuration:

    {
      "extends": ["tslint-config-airbnb", "tslint-react", "tslint-config-prettier"]
    }
    

    and here is a sample component

    import * as React from 'react';
    
    const DummyComponent = () => <div>Hello World!</div>;
    
    export default DummyComponent;
    
    

    which results in the error

    [tslint] variable name must be in lowerCamelCase or UPPER_CASE (variable-name)
    const DummyComponent: () => JSX.Element
    

    I know that it is the tslint-config-airbnb causing the issue, but I would have thought that tslint-react would have a rule for Pascal cased SFCs.

    I think that this rule is missing. I'd be happy to throw up a PR if that's the case. I just need to read up a bit on creating rules.

    Reviewed by nickytonline at 2017-11-01 15:02
  • 3. add rule jsx-sort-props to order props alphabetically, optionally by type

    Addresses #8

    Also see similar update in tslint: https://github.com/palantir/tslint/pull/2831

    CHANGELOG.md entry:

    [new-rule] jsx-sort-props: Sort props alphabetically and optionally by type (spread, shorthand, longhand)

    Reviewed by SteveByerly at 2017-05-30 04:04
  • 4. Allow jsx-no-bind and jsx-no-lambda to ignore DOMComponents

    I think function binding and anonymous functions with DOMComponent would be fine, the cost to create a function each time is not significant. So it makes sense to add a option to ignore DOMComponents.

    eslint-plugin-react has added this option as https://github.com/yannickcr/eslint-plugin-react/issues/1238

    Reviewed by koba04 at 2018-09-29 06:28
  • 5. 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.

    Reviewed by tp at 2016-07-12 14:16
  • 6. Add new rule noAccessStateInSetstate

    Fixes #172 (and #80 to some extent)

    Overview of change:

    Took ESLint-plugin-React's no-access-state-in-setstate rule and implemented it in tslint-react. I know no maintainer seems to have reviewed #172 yet, but I took a swing at it anyway, hope that was okay!

    Is there anything you'd like reviewers to focus on?

    You will find that I did the checks with pretty simple string comparisons (e.g. expression.getText().indexOf("this.state.") !== -1;). I started creating the checks with actually using the AST but found that the string solution is not only imho more reliable but of course also a lot easier to write and understand. But maybe there're better ways to check it!

    No matter the way the check of the this.setState argument is implemented, there are still ways to bypass the check and creating - if you want so - false-positives.

    class MyReactComponent extend React.Component {
      // ...
      
      myFunction() {
        this.setState({
          foo: this.state.foo + 1 // Rule will detect this
        });
    
        const foo = this.state.foo;
        this.setState({
          foo: foo + 1 // Still using this.state, rule won't mark it
        });
        
        this.setState({
          foo: getFoo() // Also this.state, won't be detected
        })
      }
    
      getFoo() {
        return this.state.foo;
      }
    }
    

    You'd have to determine every variable containing (or deriving from) the current state and every functions whose return value depends on it, and then check if those variables and methods are used in this.setState. ESLint-plugin-React even does something like that. But I guess my pull request atleast offers a good starting point and will catch most of the error-prone code lines. Since English isn't my first language, all texts (e.g. rule description) might be improvable :-) Looking forward to your review!

    Reviewed by cheeZery at 2018-12-08 21:12
  • 7. jsx-max-props-per-line

    Hey All, new to typescript and JS has this jsx rule for formatting the structure of JSX props. I would like this:

    <img src={logo} className={style.appLogo} alt="logo" />
    

    to look like:

          <img 
            src={logo} 
            className={style.appLogo} 
            alt="logo"
         />
        // or
        <img src={logo} 
             className={style.appLogo} 
             alt="logo" />
    
    

    with the closing tag and opening prop optionally on a new line.

    I think it would work with jsx-alignment for aligning the props.

    Is there any possibility to get something like this setup already? Note that if I have multiple props, or long props, that softwrap it results in the first formatting above. However I'd like to define the maximum number of props on a line before it wraps (1 in the above examples).

    Reviewed by andy9775 at 2018-05-19 02:31
  • 8. [jsx-curly-spacing] False positive with render props

    The following code is causing false positive on this rule.

    tslint-react: 3.4.0

    <Route
      children={({ location, history }) =>
        store.auth.isAuthenticated ? (
          <Redirect to={location.state.from} />
        ) : null
      } // Error here: There should be no space before } (jsx-curly-spacing)
    />
    

    I might add that code is auto formatted by Prettier so I cannot write it differently :)

    /cc @bolatovumar

    Reviewed by FredyC at 2018-01-30 14:55
  • 9. 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
    Reviewed by adidahiya at 2016-12-15 23:51
  • 10. Add rule for React Hooks

    I created a rule for detecting improper uses of React Hooks. For more information about the rule take a look at the tslint-react-hooks repository.

    This PR integrates the react-hooks-nesting into this repository.

    I built tslint-react with the newly added rule and it works correctly with both react-hooks-nesting and built in this repository (example that reports both react-hooks-nesting for using a hook inside if and jsx-wrap-multiline):

    image

    tslint.json contained only the following:

    {
      "extends": "tslint-react"
    }
    

    This PR is related to #186.

    Reviewed by Gelio at 2019-02-13 07:26
  • 11. react/prefer-stateless-function for tslint-react

    Hello. When using ESlint with React I always enable the following rule:

    https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/prefer-stateless-function.md

    I was not able to find the same kind of rule for tslint-react.

    1. Is this something you feel would fit well into the project?
    2. If so, can I submit a pull-request to add the feature?

    Thanks

    Reviewed by dreadwail at 2017-09-17 17:15
  • 12. Roadmap: tslint-react -> eslint-plugin-react

    Similar to https://github.com/palantir/tslint/issues/4534... note that all formatting rule requests will be declined because we recommend using Prettier for code formatting.

    You may also use this thread as a place to submit feedback about the state of eslint-plugin-react w/ TypeScript.


    Update (June 2019): a more concrete roadmap timeline:

    • August 1st, 2019: Stop accepting new core rules. Still accept bug fixes, minor features, and rule enhancements. Custom rules are always an option and can be maintained outside this repo.
    • November 1st, 2019: Stop accepting features or rule enhancements (with the exception of ones that make migrating to typescript-eslint easier). Still accept bug fixes.
    • January 1st, 2020: Stop accepting anything except security fixes.
    • December 1st, 2020: Stop accepting any PRs 🎉
    Reviewed by adidahiya at 2019-03-12 23:26
Court.css - A naive CSS Utility framework based on JSX and css custom properties

court.css ?? A (work in progress) JSX-based, CSS utility framework with a predic

Mar 14, 2022
A react component available on npm to easily link to your project on github and is made using React, TypeScript and styled-components.

fork-me-corner is a react component available on npm to easily link to your project on github and is made using React, TypeScript and styled-components.

Feb 27, 2022
A toolchain for React component styling.

Radium yarn add radium # or npm install --save radium Radium is a set of tools to manage inline styles on React elements. It gives you powerful stylin

May 10, 2022
Seamless mapping of class names to CSS modules inside of React components.
Seamless mapping of class names to CSS modules inside of React components.

React CSS Modules React CSS Modules implement automatic mapping of CSS modules. Every CSS class is assigned a local-scoped identifier with a global un

May 7, 2022
CSS media queries in react - for responsive design, and more.

react-responsive Information Package react-responsive Description Media queries in react for responsive design Browser Version >= IE6* Demo The best s

May 12, 2022
Flexibly styled chat-widget for your react apps.
Flexibly styled chat-widget for your react apps.

Flexibly styled chat-widget for your react apps. It was mainly created for integration with chat-bots in messengers.

Jun 11, 2021
React visual primitives with first-class TypeScript support and a tiny footprint.

tsstyled React visual primitives with first-class TypeScript support and a tiny footprint. TL;DR: This library is a styled-components rewrite that is

Apr 7, 2022
Imersão React.js 3º edição. Project using ReactJS, Next JS, and Styled Components for the week challenge by Alura. We created a social network inspired by Orkut.

Example app with styled-components This example features how you use a different styling solution than styled-jsx that also supports universal styles.

Jul 19, 2021
Dynamic Styles for React Native and Expo Web
Dynamic Styles for React Native and Expo Web

react-native-swag-styles Dynamic Styles for React Native and Expo Web Highlights Dynamic. Based on React Hook. It automatically re-renders when necess

May 17, 2022
CSS Maid 🧹 A tool made for React.js to clean up CSS default styling! Give your CSS a nice reset and style with less hassle!
CSS Maid 🧹 A tool made for React.js to clean up CSS default styling! Give your CSS a nice reset and style with less hassle!

CSS Maid ?? What is it? CSS Maid is a tool for React.js that helps clean up & reset default css! It resets default padding, remove text-decoration on

Sep 1, 2021
🏠 Airbnb website using React, Next.js and Tailwind CSS
🏠 Airbnb website using React, Next.js and Tailwind CSS

This example shows how to use Tailwind CSS (v2.2) with Next.js. It follows the steps outlined in the official Tailwind docs.

May 2, 2022
Create tailwind css react components like styled components with classes name on multiple lines

Create Tailwind CSS React components like styled components with class names on multiple lines and conditional class rendering

May 11, 2022
Whirlwind is a utility-first styling framework specifically designed for React Native. It is heavily inspired by Tachyons and Tailwind CSS and uses low-level building blocks for rapidly building custom designs.

React Native Whirlwind ??️ A utility-first CSS framework designed for React Native. Whirlwind is a utility-first CSS framework specifically designed f

May 6, 2022
Style your React components with simplicity using css inside your comments.

Style your React components with simplicity using css inside your comments.

Oct 12, 2021
Minimal and performant React component library built on styled-components

Minimal and performant React component library built on styled-components

Jan 3, 2022
This repository allows you to create a React template component folder. It optionally includes scss and css files

Generate-React-Components - grc grc let you generate react components in typescript in a folder you specify and it will include .tsx, .scss, .css file

Nov 26, 2021
Vite plugin that emulates Scoped CSS for React components

vite-react-css Vite plugin that emulates Scoped CSS for React components (using generated class names) Compatible with SSR Automatic code-splitting Ho

Feb 7, 2022
Simples Projeto Desenvolvido durante o programa DevInHouse do SENAI-SC, com o intúito de desenvolver um formulário em React utilizando Styled Components
Simples Projeto Desenvolvido durante o programa DevInHouse do SENAI-SC, com o intúito de desenvolver um formulário em React utilizando Styled Components

Simple Styled Form Simples Projeto Desenvolvido durante o programa DevInHouse do SENAI-SC, com o intúito de desenvolver um formulário em React utiliza

Oct 29, 2021
🌐 ― React/Next.js/TailwindCSS portfolio

?? ― React/Next.js/TailwindCSS portfolio

May 14, 2022