Skip to content

Latest commit

 

History

History
107 lines (76 loc) · 2.3 KB

jsx-no-literals.md

File metadata and controls

107 lines (76 loc) · 2.3 KB

Prevent usage of string literals in JSX (react/jsx-no-literals)

There are a couple of scenarios where you want to avoid string literals in JSX. Either to enforce consistency and reducing strange behaviour, or for enforcing that literals aren't kept in JSX so they can be translated.

Rule Details

In JSX when using a literal string you can wrap it in a JSX container {'TEXT'}. This rules by default requires that you wrap all literal strings. Prevents any odd artifacts of highlighters if your unwrapped string contains an enclosing character like ' in contractions and enforces consistency.

The following patterns are considered warnings:

var Hello = <div>test</div>;

The following patterns are not considered warnings:

var Hello = <div>{'test'}</div>;

Options

There are two options:

  • noStrings(false default) - Enforces no string literals used as children, wrapped or unwrapped.
  • validateProps(false default) - Enforces no literals used in props, wrapped or unwrapped.

To use, you can specify like the following:

"react/jsx-no-literals": [<enabled>, {"noStrings": true, "validateProps": true}]

With noStrings set to true, the following are considered warnings:

var Hello = <div>test</div>;
var Hello = <div>{'test'}</div>;

The following are not considered warnings:

// When using something like `react-intl`
var Hello = <div><Text {...message} /></div>
// When using something similar to Rails translations
var Hello = <div>{translate('my.translation.key')}</div>

With validateProps set to true, the following are considered warnings:

var Hello = <div class='xx' />;
var Hello = <div class={'xx'} />;
var Hello = <div class={`xx`} />;
var Hello = <div event={()=>{}} />;

The following are not considered warnings:

// spread props object
var Hello = <Text {...props} />
// use variable for prop values
var Hello = <div class={xx} />
// cache 
class Comp1 extends Component {
  asdf() {}

  render() {
    return (
      <div onClick={this.asdf}>
        {'asdjfl'}
        test
        {'foo'}
      </div>
    );
  }
}

When Not To Use It

If you do not want to enforce any style JSX literals, then you can disable this rule.