LoginSignup
6
0

ReactでのCSSの使用

Last updated at Posted at 2024-02-16

普通の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>
  )
}
6
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
6
0