Help us understand the problem. What is going on with this article?

styled-componentsをTypescriptで使う

styled-components ✖️ Typescript

Typescriptでstyled-componentsを書く時に情報が少なかったので、いくつか

型定義

propsの型を定義するときは、次のようにジェネリクスで指定する

interface Props {
  color: string
}
const Sample = styled.div<Props>`
  color: ${(props) => {
    return props.color
  }}
`

例えば、buttonを属性ごとに色を変えたいときは

const Button = styled.button<{primary?: boolean}>`
  background: transparent;
  color: black;
  border: 2px solid black;
  width: 10em;
  ${props =>
    props.primary &&
    css`
      border: 2px solid skyblue;
    `}
`;
<Button>not primary</Button>
<Button primary>primary</Button>

スクリーンショット 2020-08-30 15.04.01.png

条件分岐

また、if文を使ってスタイルを適用することも可能。
例えば、typeというpropsを適用して色を変化させるときは、こんな感じ。

interface Props {
  type: 'SUCCESS' | 'FAIL';
}

const Flash = styled.div<Props>`
  text-align: center;
  margin: 5em;
  color: black;
  width: 10em;
  opacity: 0.8;
  background-color: ${props => {
    switch (props.type) {
      case 'SUCCESS':
        return 'rgba(32, 153, 134, 0.9)';
      case 'FAIL':
        return 'rgba(230, 65, 30, 1)';
      default:
        return 'rgba(32, 153, 134, 0.9)';
    }
  }};
`;

const Wrapper = styled.div`
  display: flex;
  align-items: center;
`;

const Sample: FC = () => {
  return (
    <Wrapper>
      <Flash type="SUCCESS">success</Flash>
      <Flash type="FAIL">fail</Flash>
    </Wrapper>
  );
};

スクリーンショット 2020-08-30 15.28.37.png

既存のcomponentを上書きしたいとき

typescriptとは関係ないですが、例えば基本の形はsemantic-uiなどのコンポーネントを使用したいが、色だけ変えたい時

import {Button} from 'semantic-ui-react';
const StyledButton = styled(Button)`
  margin: 20px !important;
  background: skyblue !important;
`;
<StyledButton>styled button</StyledButton>

スクリーンショット 2020-08-30 15.37.55.png

Tak0325
React, Typescript, Ruby on Rails, GCP, Spring Boot
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした