chakra-uiなどのuiライブラリを使ってUIを作っていると、スタイリング用のpropsが冗長になったりする。
テーマいじったりコンポーネント化したりできればいいけど、そこまではしたくない・・・みたいなとき
<Text fontSize="0.875rem" fontWeight={400}>hello world1</Text>
<Text fontSize="0.875rem" fontWeight={400}>hello world2</Text>
<Text fontSize="0.875rem" fontWeight={400}>hello world3</Text>
以下のtextStylesのような定数を定義しておきgetTextStylesで取得してスプレッド演算子で展開する。
それっぽい名前をつけてその粒度でコンポーネントのスタイル設定しておけば、変更も容易だし、grepで影響範囲もわかるから良さそうだと思った。
const textStyles = {
"text-md": {
fontSize: "0.875rem",
fontWeight: 400,
}
} as const;
type TextStyles = keyof typeof textStyles;
function getTextStyles(name: TextStyles) {
return textStyles[name];
}
function App() {
return (
<>
<Text {...getTextStyles("text-md")}>hello world1</Text>
<Text {...getTextStyles("text-md")}>hello world2</Text>
<Text {...getTextStyles("text-md")}>hello world3</Text>
</>
)
}
他に良い方法あったら教えてほしいです。
chakra uiだったらdefineStyleを使うと型がついて補完されて良い。
const textStyles = {
"text-md": defineStyle({
fontSize: "1rem",
// ここ入力するときに補完される
})
}
一応Chakra uiにはtextStylesやlayerStylesといった似たような機能が備わっている。
https://chakra-ui.com/docs/styled-system/text-and-layer-styles
const theme = extendTheme({
textStyles: {
"text-md": {
fontSize: "0.875rem",
},
},
});
function Page() {
return (
<Box textStyle="text-md">hogehoge</Box>
)
}
ただし、これはButtonやHeadingなどのスタイルを上書きできない。BoxやFlex, Textなどのstyled-systemのコンポーネントにしか適用できない。
// これは反映されない
<Button textStyle="text-md"></Button>