この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。
React Atomic Components の 実装パターン #React
はじめに
Atomic Components の抽象度合いの向上を目的としています
Atomic Components
抽象度低めパターン
atoms配下の、汎用的なコンポーネント
// atoms/MyInput
export const MyInput: React.FC<Props> = (props) => {
// 省略
}
// atoms/MyButton
export const MyButton: React.FC<Props> = (props) => {
// 省略
}
molecules配下の、汎用的なコンポーネント
import MyInput from '@component/atoms/MyInput'
import MyButton from '@component/atoms/MyButton'
const MyForm: React.FC<Props> = (props) => (
<>
<MyInput/>
<MyInput/>
<MyInput/>
<MyButton/>
</>
)
Atomic Components IF
抽象度高めたパターン
atoms配下の、汎用的なコンポーネント
// atoms/MyInput
export const MyInput: React.FC<Props> = (props) => {
// 省略
}
// atoms/MyButton
export const MyButton: React.FC<Props> = (props) => {
// 省略
}
interface層に配置
export type Factoy<T> = () => T
molecules配下
atomsを返す arrow function
// molecules/MyForm/IF
import MyInput from '@component/atoms/MyInput'
import MyButton from '@component/atoms/MyButton'
import Factoy from '@IF/Factoy'
export type MyForm = {
MyInput: typeof MyInput
MyButton: typeof MyButton
}
export const myFormComponents: Factoy<MyForm>) = () => ({
MyInput,
MyButton
})
汎用的なコンポーネント
コンポーネント自体を受け取る事で、抽象度やテストのしやすさの向上
// Molecules/MyForm
import Factoy from '@IF/Factoy'
import MyForm from './IF'
type Props = {
factoy: Factoy<MyForm>
}
const MyForm: React.FC<Props> = (props) => {
const {MyInput, MyButton} = props.factoy()
return (<>
<MyInput/>
<MyInput/>
<MyInput/>
<MyButton/>
</>)
}
まとめ
課題として、Ecosystems
層の お仕事は増えそうです...
ですが、配下の抽象度やテストのしやすさは、向上したと思います