0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Reactで冗長なpropsをまとめる

0
Last updated at Posted at 2024-02-07

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>
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?