別の HTML 要素に、同じ CSS を使い回す便利な方法を見つけたのでメモしておきます
Styled-Components (CSS-in-JS) で 異なる HTML 要素に同じスタイルを適用したいことがあります
例えば、私は button タグと a タグに同じスタイルを適用したいときがよくあります
import { styled } from 'styled-components'const Button = styled.button`width: 100px;border-radius: 8px;color: red;`const Anchor = styled.a`width: 100px;border-radius: 8px;color: red;`
このような場合は css ヘルパーを使うと便利です
以下のようにすると一括で同じスタイルを適用することが可能です 🎉
import { styled, css } from 'styled-components'const sharedStyles = css`width: 100px;border-radius: 8px;color: red;`const Button = styled.button`${sharedStyles}`const Anchor = styled.a`${sharedStyles}`
ちなみに props も受け付けることができます
HTML 要素側でも同じ props を受け付けるようにしておけば OK です
import { styled, css } from 'styled-components'const sharedStyles = css<{ $color?: string }>`width: 100px;border-radius: 8px;color: ${props => props.$color || 'red'};`const Button = styled.button<{ $color?: string }>`${sharedStyles}`const Anchor = styled.a<{ $color?: string }>`${sharedStyles}`
おわりに
スタイルが長くなると2つ以上の保守が大変になるので、まとめておくことはいいことかなと思います 🐬
二重定義しまくってた時代があったので、これに修正したいですねー 🐶