2022.05.25
Chakra UIを使用して、「Button」コンポーネントの初期スタイルを設定する時に少し躓いたのでメモ。
基本的にChakraは初期設定なしでも使用することが可能。
しかし、hover、activeなどに対して初期スタイルがあたっており各コンポーネントを呼び出す度に打ち消しを行わないといけないのは面倒である。
そこでextendThemeというものが用意されておりCSSの設定を行うことができる。
下記はextendThemeのメモ。
import {
extendTheme,
withDefaultProps,
type ThemeConfig,
type ComponentStyleConfig,
} from '@chakra-ui/react'
// Dark Modeの設定ができる
const config: ThemeConfig = {
// 初期Modeは、light・dark・systemから選択できる。
initialColorMode: 'light',
useSystemColorMode: false,
}
// html タグを指定してスタイルの上書きができる
const styles = {
global: {
body: {
bg: 'sTMainColor',
color: 'sTParagraph',
},
},
}
// コンポーネントを指定してスタイルの上書きができる
const Heading: ComponentStyleConfig = {
baseStyle: {
color: 'sTHeading',
},
}
const theme = extendTheme(
withDefaultProps({
defaultProps: {
variant: 'unstyled',
size: 'auto',
},
components: ['Button'],
}),
{
components: {
Heading,
},
semanticTokens: {
colors: {
sTMainColor: {
_light: '#F9F4EF',
_dark: '#020826',
},
sTSecondColor: {
_light: '#8C7851',
_dark: '#F9F4EF',
},
sTHeading: {
_light: '#020826',
_dark: '#F9F4EF',
},
sTParagraph: {
_light: '#716040',
_dark: '#F9F4EF',
},
sTButton: {
_light: '#FFFFFE',
_dark: '#020826',
},
sTNotice: '#EB5757',
},
},
styles,
config,
},
)
export default theme
各コンポーネントには基本的に「colorScheme」と「variant」と「size」のdefault props設定されていることが多い。
このdefault propsはextendThemeで指定したスタイルより優先度が高いのでスタイルの変更が反映されない。
そこで各default propsの初期値を上書くことができる。
● withDefaultColorScheme:colorSchemeの初期値の上書き
● withDefaultSize:sizeの初期値の上書き
● withDefaultVariant:variantの初期値の上書き
● withDefaultProps:Propsに渡される初期値の上書き
基本的には、「withDefaultProps」で全て更新できるので迷ったらこれを使うといい。
プロジェクト内で使用するコンポーネントに関しては初期設定を行っておくことでスタイルの統一性、開発体験の向上につながるのでしっかりと設定していきたい。