LoginSignup
0
1

More than 1 year has passed since last update.

Styled-Componentsとpropsを使ったスタイリングの備忘録

Posted at

自分用備忘録。
Styled-Componentsを使って、propsを渡して動的にスタイリングを適用する方法をまとめてみる。今回はChakraUIのButtonをベースにした例で説明していく。

Chakra UIのButtonにpropsを渡して動的にスタイルを適用する方法

<ButtonStyle hogeProps={true} />
const ButtonStyle = styled(Button)<{hogeProps:boolean}>`
  color: ${props => props.hogeProps ? 'trueの時の処理' : 'falseの時の処理'};
`;

この例ではhogePropsという名前のpropsをButtonStyleコンポーネントに渡している。
Styled-Component内で、三項演算子を使ってhogePropsがtrueの場合とfalseの場合で異なるスタイルを適用している。

ついでに位置を動的に設定するModalContentStyleコンポーネントを作成する方法もば。

位置を動的に設定するModalContentStyleコンポーネントの作成

<ModalContentStyle x={positionX} y={positionY} />
const ModalContentStyle = styled(ModalContent)<{ x?: number; y?: number }>`
  border: 1px solid #fefefe;
  ${({ x, y }) => // x , y があるときのみ下記のCSSを適用
    x !== undefined && y !== undefined
      ? `
        left: ${x}px;
        top: ${y}px;
        transform: translate(-100%, 0);
        `
      : ""}
`;

この例では、xとyという名前のpropsをModalContentStyleコンポーネントに渡している。xとyがどちらも定義されている場合のみ、位置を動的に設定するCSSが適用されるようにしている。

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