LoginSignup
16
3

More than 5 years have passed since last update.

ReactではPropsにtrueを渡す際は作法がある。

Last updated at Posted at 2017-07-27

Reactでpropstrueを渡すときに、どう記述するか?

<MyComponent testProps={true} />

こういう時にair-bnbのLinterを導入していると、warningが出る。
これですね

このLintに従うと、こうなる。

<MyComponent testProps />

なぜこれで、propstrueが渡せるのか?

答えは公式にあった!!

公式を参照。

どうやら、コンパイルの際にtrueを渡してくれる模様。
さらに、省略形を推奨している。。。と思う。
読み間違っていて逆を言っているかも:joy:

理由としては、ES6のショートハンドと間違うかららしい。
以下のような形で変数footrueを代入して渡すような時に、
{foo: foo}のショートハンド{foo}と紛らわしいという意味だと思われる。
「変数fooを探してtrueを見つけるよりは、最初から省いておいてtrueを渡しているの明示した方が分かりやすい」という意味と解釈しました。

it can be confused with the ES6 object shorthand {foo} which is short for {foo: foo} rather than {foo: true}が上手く訳せない・・・

class TestComponent extends React.Component{
  render(){
    return(
      <div>
        <h1>{this.props.children}</h1>
        <h2>{`${this.props.aho}`}</h2>
      </div>
    );
  }
}

const foo = true;
ReactDOM.render(
  <TestComponent aho={foo}>hogehoe00000</TestComponent>,
  document.getElementById('b4')
);

私もLintがなくても、ここまで意識してコードを書けるようになりたい。
道は長い・・・

16
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
3