jsx-eslint/eslint-plugin-react

Rule proposal: disallow string interpolation for className

オープン

#460 opened on 2016/02/22

 (1 件のコメント) (4 件のリアクション) (0 人の担当者)JavaScript (2,731 件のフォーク)batch import
help wantednew rule

Repository metrics

Stars
 (9,293 個のスター)
PR merge metrics
 (PR metrics pending)

説明

Using string interpolation in classNames can make it difficult to determine whether some CSS is actually used in your project. To make this easier, some folks might want to enforce preventing string interpolation in classNames.

Bad:

function MyComponent({ someProp }) {
  const classNames = `my-component my-component-${someProp}`;

  return (
    <div className={classNames}>
      Hi mom
    </div>
  )
}

Bad:

function MyComponent({ someProp }) {
  const classNames = 'my-component my-component-' + someProp;

  return (
    <div className={classNames}>
      Hi mom
    </div>
  )
}

Bad:

function MyComponent({ someProp }) {
  const classNames = ['my-component'];
  classNames.push('my-component-' + someProp);

  return (
    <div className={classNames.join(' ')}>
      Hi mom
    </div>
  )
}

Good:

function MyComponent({ someProp }) {
  const classNames = ['my-component'];
  if (someProp === 'some-value') {
    classNames.push('my-component-some-value');
  } else if (someProp === 'another-value') {
    classNames.push('my-component-another-value');
  }

  return (
    <div className={classNames.join(' ')}>
      Hi mom
    </div>
  )
}

Of course, the classnames package can be useful here.

I don't know yet, but this may be useful for other props, so perhaps it could be configured for a list of props.

コントリビューターガイド