Reactを採用したTypeScriptプロジェクトにおける命名規則
React を採用している TypeScript プロジェクトにおいて、命名規則が揃ってなさそう!というご指摘をもらったので調べてたんですが、以下のような疑問を投げかけたところ @rukiadia と @takf-jp にスパッと解決してもらいました。
takoba
component は UpperCamel でそれ以外は lowerCamel って何が根拠になってるんですかね…👀
rukiadia
Reactでユーザ定義のコンポーネントを使う場合、先頭を大文字にしないといけなかったはず。
https://reactjs.org/docs/jsx-in-depth.html#user-defined-components-must-be-capitalized
「request周りはコンポーネントではないので、UpperCaseにする必要はない」が @takf-jp の言いたいことなのかなーと理解してます。
takf-jp
- Reactではコンポーネントは UpperCamel でないとコンパイルエラーになる
- https://reactjs.org/docs/jsx-in-depth.html#user-defined-components-must-be-capitalized
- lowerCamel は元々 JS の開発での慣習
- https://typescript-jp.gitbook.io/deep-dive/styleguide#filename
以上が根拠?というか慣習から来ている感じです
ほえ〜〜なるほどな〜〜〜
URL もらったから、もうちょい具体的に解説してみるぞ!
なるほど? lowercase からはじめると HTML タグとして認識しようとしちゃうのね〜〜
cf. https://reactjs.org/docs/jsx-in-depth.html#user-defined-components-must-be-capitalized
User-Defined Components Must Be Capitalized
When an element type starts with a lowercase letter, it refers to a built-in component like <div> or <span> and results in a string 'div' or 'span' passed to React.createElement. Types that start with a capital letter like <Foo /> compile to React.createElement(Foo) and correspond to a component defined or imported in your JavaScript file.
We recommend naming components with a capital letter. If you do have a component that starts with a lowercase letter, assign it to a capitalized variable before using it in JSX.
で、多くの JavaScript プロジェクトだと lowerCamel が慣習になってるんだな〜〜
cf. https://typescript-jp.gitbook.io/deep-dive/styleguide#filename
ファイル名
camelCaseを使ってファイルに名前を付けます。例えばaccordion.tsx、myControl.tsx、utils.ts、map.tsなどです。
> 理由:多くのJSチームで慣習的です。
学んだ!ありがとう @rukiadia & @takf-jp !🥰
#Techlog #React #TypeScript #JavaScript #命名規則 #慣習