普通のCSSの使用
インライン Style(推奨しない)
下記の条件が必要です。
- HTMLスタイルと同じ、要素のインライン スタイルです
- 文字列ではなく、JS オブジェクトの形式である必要があります
- スタイル名は「fontSize」のようにキャメルケースで表記する
<span style={{color: 'green'}}>在庫あり</span>
classNameの使用
- HTMLクラスと同様にCSSスタイル名をclassNameで設定する
- JSの
class
と重複するため、className
に名前を変更する - clsx または classnames 条件を使用して判定可能
CSS-in-js (推奨)
- CSSをJSで記述する(コンポーネントコード内)
- CSS クラス名の重複を心配する必要はない
- CSS-in-js はツールの名前ではなくソリューションです
Styled-componentsの使用
ドキュメント
https://styled-components.com/
// Button コンポーネント
type ButtonPropsType = {
primary?: boolean
}
const Button = styled.button<ButtonPropsType>`
background: transparent;
border-radius: 3px;
border: 2px solid palevioletred;
color: palevioletred;
margin: 0 1em;
padding: 0.25em 1em;
${(props) =>
props.primary &&
css`
background: palevioletred;
color: white;
`}
`
// Containerコンポーネント
const Container = styled.div`
text-align: center;
`
const Demo: FC = () => {
return (
<div>
<p>styled-components demo</p>
<Container>
<Button>Normal Button</Button>
<Button primary>Primary Button</Button>
</Container>
</div>
)
}