7839

雑草魂エンジニアブログ

Vue.jsエンジニアのReact入門 - Vue.js ライクな ReactComponent の書き方

Vue.js エンジニアの React 入門。
React の実装方法を Vue.js と対比しながら理解を深めていくシリーズ。

これまでに、以下の内容についてまとめてきたので、参考にご覧ください。

今回は、「Componentの書き方」について紹介する。

ただし、今回は対比するというよりは、ReactComponent をどのように書くのがいいかを考えた末に、Vue ライクな構成が一番可読性がよく、リファクタリングしやすいのではないかという考えになり、Vue.js ライクな ReactComponent の書き方を紹介する。Vue.js の書き方に慣れていることも大きな理由ではあるが、Vue.js エンジニアにとって導入しやすいと思われるので、参考になれば嬉しい。

Vue.js

Vus.js のコンポーネントにおいては、<script><template><style> の3層構造で、コンポーネントを書く。

f:id:serip39:20200726015115p:plain

詳細は、公式のスタイルガイドを参照してみてください。

jp.vuejs.org

React

今回の構成では、以下を想定している。

  • TypeScript
  • styled-components

ReactComponent の書き方は、以下のようにすることで、Vue.jsライクな構成で書くことができる。

f:id:serip39:20200726015842p:plain

本構成に関しては、以下の記事を参考にした。(本当にわかりやすい構成をありがとうございました。)

qiita.com

こちらの記事で述べられている、以下のSFC(Stateless Functional Component)の5層の順番を入れ替えて、よりVue.js ライクな構成とした。

// (1) import層
import React from 'react'
import styled from 'styled-components'
// (2) Types層
type ContainerProps = {...}
type Props = {...} & ContainerProps
// (3) DOM層
const Component: React.FC<Props> = props => (...)
// (4) Style層
const StyledComponent = styled(Component)`...`
// (5) Container層
const Container: React.FC<ContainerProps> = props => {
  return <StyledComponent {...props} />
}

この構成で書くことで、個人的には、上から下に流れるように読むことができるので、可読性が向上したように思っている。

// (1) Script( import層/Types層/Container層)
import React from 'react'
import styled from 'styled-components'
type ContainerProps = {...}
const Container: React.FC<ContainerProps> = props => {
  return <StyledComponent {...props} />
}

// (2) HTML(Types層/DOM層)
type Props = {...} & ContainerProps
const Component: React.FC<Props> = props => (...)

// (3) CSS(Style層)
const StyledComponent = styled(Component)`...`

まとめ

今回、Vue.js ライクな ReactComponent の書き方を紹介した。React の場合は、Vueのような型がないので、自由に書ける分、最適な書き方はどうすべきなのか、まだ暗中模索中である。是非、オススメがあれば、教えていただきたいです。よろしくお願いします。

それでは、ステキな開発ライフを。